encoding-guesser: Fall back to windows-1252 when UTF-8 can't be right.
[pspp] / src / libpspp / u8-istream.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2010, 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 "u8-istream.h"
20
21 #include <assert.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <iconv.h>
25 #include <limits.h>
26 #include <stdint.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <unistr.h>
32
33 #include "libpspp/assertion.h"
34 #include "libpspp/cast.h"
35 #include "libpspp/compiler.h"
36 #include "libpspp/encoding-guesser.h"
37 #include "libpspp/i18n.h"
38
39 #include "gl/c-strcase.h"
40 #include "gl/localcharset.h"
41 #include "gl/minmax.h"
42
43 enum u8_istream_state
44   {
45     S_AUTO,                     /* Stream encoding not yet known. */
46     S_UTF8,                     /* Stream encoding is known to be UTF-8. */
47     S_CONVERT                   /* Stream encoding is known but not UTF-8. */
48   };
49
50 struct u8_istream
51   {
52     int fd;
53     iconv_t converter;
54     enum u8_istream_state state;
55
56     char *buffer;
57     char *head;
58     size_t length;
59
60     char outbuf[4];
61     size_t outlen;
62   };
63
64 static ssize_t fill_buffer (struct u8_istream *);
65
66 /* Opens FILENAME, which is encoded in FROMCODE, for reading as an UTF-8
67    stream, passing FLAGS to the open() function.  Returns a new u8_istream if
68    successful, otherwise returns NULL and sets errno to an appropriate value.
69
70    The accepted forms for FROMCODE are listed at the top of
71    encoding-guesser.h. */
72 struct u8_istream *
73 u8_istream_for_file (const char *fromcode, const char *filename, int flags)
74 {
75   struct u8_istream *is;
76   int fd;
77
78   assert (!(flags & O_CREAT));
79
80   fd = open (filename, flags);
81   if (fd < 0)
82     return NULL;
83
84   is = u8_istream_for_fd (fromcode, fd);
85   if (is == NULL)
86     {
87       int save_errno = errno;
88       close (fd);
89       errno = save_errno;
90     }
91
92   return is;
93 }
94
95 /* Creates and returns a new u8_istream that reads its input from FD.  Returns
96    a new u8_istream if successful, otherwise returns NULL and sets errno to an
97    appropriate value.
98
99    The accepted forms for FROMCODE are listed at the top of
100    encoding-guesser.h. */
101 struct u8_istream *
102 u8_istream_for_fd (const char *fromcode, int fd)
103 {
104   struct u8_istream *is;
105   const char *encoding;
106
107   is = malloc (sizeof *is);
108   if (is == NULL)
109     return NULL;
110
111   is->fd = fd;
112   is->converter = (iconv_t) -1;
113   is->buffer = malloc (U8_ISTREAM_BUFFER_SIZE);
114   if (is->buffer == NULL)
115     goto error;
116   is->head = is->buffer;
117   is->length = 0;
118   is->outlen = 0;
119
120   if (fill_buffer (is) < 0)
121     goto error;
122
123   encoding = encoding_guess_head_encoding (fromcode, is->buffer, is->length);
124   if (is_encoding_utf8 (encoding))
125     is->state = S_UTF8;
126   else
127     {
128       if (encoding_guess_encoding_is_auto (fromcode)
129           && !strcmp (encoding, "ASCII"))
130         is->state = S_AUTO;
131       else
132         is->state = S_CONVERT;
133
134       is->converter = iconv_open ("UTF-8",
135                                   encoding_guess_parse_encoding (fromcode));
136       if (is->converter == (iconv_t) -1)
137         goto error;
138     }
139
140   return is;
141
142 error:
143   u8_istream_free (is);
144   return NULL;
145 }
146
147 /* Closes IS and its underlying file descriptor and frees all associated
148    resources.  Returns the return value from close(). */
149 int
150 u8_istream_close (struct u8_istream *is)
151 {
152   if (is != NULL)
153     {
154       int fd = is->fd;
155       u8_istream_free (is);
156       return close (fd);
157     }
158   return 0;
159 }
160
161 /* Frees IS and associated resources, but does not close the underlying file
162    descriptor.  (Thus, the client must close the file descriptor when it is no
163    longer needed.) */
164 void
165 u8_istream_free (struct u8_istream *is)
166 {
167   if (is != NULL)
168     {
169       if (is->converter != (iconv_t) -1)
170         iconv_close (is->converter);
171       free (is->buffer);
172       free (is);
173     }
174 }
175
176 static void
177 substitute_invalid_input_byte (struct u8_istream *is)
178 {
179   assert (is->outlen == 0);
180   is->head++;
181   is->length--;
182   is->outlen = u8_uctomb (CHAR_CAST (uint8_t *, is->outbuf),
183                           0xfffd, sizeof is->outbuf);
184 }
185
186 static ssize_t
187 fill_buffer (struct u8_istream *is)
188 {
189   ssize_t n;
190
191   /* Move any unused bytes to the beginning of the input buffer. */
192   if (is->length > 0 && is->buffer != is->head)
193     memmove (is->buffer, is->head, is->length);
194   is->head = is->buffer;
195
196   /* Read more input. */
197   n = read (is->fd, is->buffer + is->length,
198             U8_ISTREAM_BUFFER_SIZE - is->length);
199   if (n > 0)
200     is->length += n;
201   return n;
202 }
203
204 static ssize_t
205 read_auto (struct u8_istream *is, char *buffer, size_t size)
206 {
207   size_t original_size = size;
208   int retval = 0;
209
210   while (size > 0)
211     {
212       if (is->length > 0)
213         {
214           size_t n_ascii;
215
216           n_ascii = encoding_guess_count_ascii (is->head,
217                                                 MIN (is->length, size));
218
219           memcpy (buffer, is->head, n_ascii);
220           buffer += n_ascii;
221           size -= n_ascii;
222
223           is->head += n_ascii;
224           is->length -= n_ascii;
225
226           if (size == 0)
227             break;
228         }
229
230       if (is->length == 0)
231         {
232           retval = fill_buffer (is);
233           if (retval > 0)
234             continue;
235           else
236             break;
237         }
238
239       /* is->head points to a byte that isn't a printable ASCII character.
240          Fill up the buffer and check for UTF-8. */
241       fill_buffer (is);
242       is->state = (encoding_guess_tail_is_utf8 (is->head, is->length)
243                    ? S_UTF8 : S_CONVERT);
244       if (size == original_size)
245         return u8_istream_read (is, buffer, size);
246       break;
247     }
248
249   return original_size - size;
250 }
251
252 static int
253 convert_iconv (iconv_t converter,
254                char **inbufp, size_t *inbytesleft,
255                char **outbufp, size_t *outbytesleft)
256 {
257   size_t n = iconv (converter, (ICONV_CONST char **) inbufp, inbytesleft,
258                     outbufp, outbytesleft);
259   return n == SIZE_MAX ? errno : 0;
260 }
261
262 static int
263 convert_utf8 (iconv_t converter UNUSED,
264               char **inbufp, size_t *inbytesleft,
265               char **outbufp, size_t *outbytesleft)
266 {
267   const uint8_t *in = CHAR_CAST (const uint8_t *, *inbufp);
268   size_t n = MIN (*inbytesleft, *outbytesleft);
269   size_t ofs = 0;
270   int error;
271
272   for (;;)
273     {
274       ucs4_t uc;
275       int mblen;
276
277       if (ofs >= n)
278         {
279           error = ofs < *inbytesleft ? E2BIG : 0;
280           break;
281         }
282
283       mblen = u8_mbtouc (&uc, in + ofs, n - ofs);
284       if (uc == 0xfffd)
285         {
286           int retval = u8_mbtoucr (&uc, in + ofs, *inbytesleft - ofs);
287           if (retval == mblen)
288             {
289               /* There's an actual U+FFFD in the input stream.  Carry on. */
290             }
291           else
292             {
293               error = (retval == -1 ? EILSEQ
294                        : retval == -2 ? EINVAL
295                        : E2BIG);
296               break;
297             }
298         }
299
300       ofs += mblen;
301     }
302
303   if (ofs > 0)
304     {
305       memcpy (*outbufp, *inbufp, ofs);
306       *inbufp += ofs;
307       *inbytesleft -= ofs;
308       *outbufp += ofs;
309       *outbytesleft -= ofs;
310     }
311
312   return error;
313 }
314
315 static ssize_t
316 read_convert (struct u8_istream *is,
317               int (*convert) (iconv_t converter,
318                               char **inbufp, size_t *inbytesleft,
319                               char **outbufp, size_t *outbytesleft),
320               char *buffer, size_t size)
321 {
322   size_t original_size = size;
323
324   while (size > 0)
325     {
326       ssize_t n_read;
327
328       if (is->outlen > 0)
329         {
330           size_t n = MIN (size, is->outlen);
331
332           memcpy (buffer, is->outbuf, n);
333           is->outlen -= n;
334           if (is->outlen > 0)
335             memmove (is->outbuf, is->outbuf + n, is->outlen);
336
337           buffer += n;
338           size -= n;
339
340           if (size == 0)
341             break;
342         }
343
344       if (is->length)
345         {
346           int error = convert (is->converter,
347                                &is->head, &is->length,
348                                &buffer, &size);
349           if (size == 0)
350             break;
351
352           switch (error)
353             {
354             case 0:
355               /* Converted all of the input into output, possibly with space
356                  for output left over.
357
358                  Read more input. */
359               break;
360
361             case EILSEQ:
362               substitute_invalid_input_byte (is);
363               continue;
364
365             case EINVAL:
366               /* Incomplete byte sequence at end of input.  Read more
367                  input. */
368               break;
369
370             default:
371               /* A real error of some kind (ENOMEM?). */
372               return -1;
373
374             case E2BIG:
375               /* Ran out of room for output.
376                  Convert into outbuf and copy from there instead. */
377               {
378                 char *outptr = is->outbuf;
379                 size_t outleft = sizeof is->outbuf;
380
381                 error = convert (is->converter,
382                                  &is->head, &is->length,
383                                  &outptr, &outleft);
384                 is->outlen = outptr - is->outbuf;
385                 if (is->outlen > 0)
386                   continue;
387
388                 switch (error)
389                   {
390                   case EILSEQ:
391                     substitute_invalid_input_byte (is);
392                     continue;
393
394                   case E2BIG:
395                   case EINVAL:
396                     continue;
397
398                   default:
399                     /* A real error of some kind (ENOMEM?). */
400                     return -1;
401                   }
402               }
403             }
404         }
405
406       assert (is->length <= MB_LEN_MAX);
407       n_read = fill_buffer (is);
408       if (n_read <= 0)
409         {
410           if (original_size != size)
411             {
412               /* We produced some output so don't report EOF or error yet. */
413               break;
414             }
415           else if (n_read == 0 && is->length != 0)
416             {
417               /* Incomplete byte sequence at end of file. */
418               substitute_invalid_input_byte (is);
419             }
420           else
421             {
422               /* Propagate end-of-file or error to caller. */
423               return n_read;
424             }
425         }
426     }
427
428   return original_size - size;
429 }
430
431 /* Reads up to SIZE bytes of UTF-8 text from IS into BUFFER.  Returns the
432    number of bytes read if successful, 0 at end of file, or -1 if an error
433    occurred before any data could be read.  Upon error, sets errno to an
434    appropriate value. */
435 ssize_t
436 u8_istream_read (struct u8_istream *is, char *buffer, size_t size)
437 {
438   switch (is->state)
439     {
440     case S_CONVERT:
441       return read_convert (is, convert_iconv, buffer, size);
442
443     case S_AUTO:
444       return read_auto (is, buffer, size);
445
446     case S_UTF8:
447       return read_convert (is, convert_utf8, buffer, size);
448     }
449
450   NOT_REACHED ();
451 }
452
453 /* Returns the file descriptor underlying IS. */
454 int
455 u8_istream_fileno (const struct u8_istream *is)
456 {
457   return is->fd;
458 }
459 \f
460 /* Test functions.
461
462    These functions are probably useful only for white-box testing. */
463
464 /* Returns true if the encoding of the file being read by IS is not yet
465    known. */
466 bool
467 u8_istream_is_auto (const struct u8_istream *is)
468 {
469   return is->state == S_AUTO;
470 }
471
472 /* Returns true if the encoding of the file being read by IS has been
473    determined to be UTF-8. */
474 bool
475 u8_istream_is_utf8 (const struct u8_istream *is)
476 {
477   return is->state == S_UTF8;
478 }