Assume the standard headers exist.
[gnulib.git] / lib / localcharset.c
1 /* Determine a canonical name for the current locale's character encoding.
2
3    Copyright (C) 2000-2006 Free Software Foundation, Inc.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License along
16    with this program; if not, write to the Free Software Foundation,
17    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
18
19 /* Written by Bruno Haible <bruno@clisp.org>.  */
20
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
24
25 /* Specification.  */
26 #include "localcharset.h"
27
28 #include <stddef.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <stdlib.h>
32
33 #if defined _WIN32 || defined __WIN32__
34 # define WIN32_NATIVE
35 #endif
36
37 #if defined __EMX__
38 /* Assume EMX program runs on OS/2, even if compiled under DOS.  */
39 # define OS2
40 #endif
41
42 #if !defined WIN32_NATIVE
43 # if HAVE_LANGINFO_CODESET
44 #  include <langinfo.h>
45 # else
46 #  if HAVE_SETLOCALE
47 #   include <locale.h>
48 #  endif
49 # endif
50 # ifdef __CYGWIN__
51 #  define WIN32_LEAN_AND_MEAN
52 #  include <windows.h>
53 # endif
54 #elif defined WIN32_NATIVE
55 # define WIN32_LEAN_AND_MEAN
56 # include <windows.h>
57 #endif
58 #if defined OS2
59 # define INCL_DOS
60 # include <os2.h>
61 #endif
62
63 #if ENABLE_RELOCATABLE
64 # include "relocatable.h"
65 #else
66 # define relocate(pathname) (pathname)
67 #endif
68
69 #if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ || defined __EMX__ || defined __DJGPP__
70   /* Win32, Cygwin, OS/2, DOS */
71 # define ISSLASH(C) ((C) == '/' || (C) == '\\')
72 #endif
73
74 #ifndef DIRECTORY_SEPARATOR
75 # define DIRECTORY_SEPARATOR '/'
76 #endif
77
78 #ifndef ISSLASH
79 # define ISSLASH(C) ((C) == DIRECTORY_SEPARATOR)
80 #endif
81
82 #if HAVE_DECL_GETC_UNLOCKED
83 # undef getc
84 # define getc getc_unlocked
85 #endif
86
87 /* The following static variable is declared 'volatile' to avoid a
88    possible multithread problem in the function get_charset_aliases. If we
89    are running in a threaded environment, and if two threads initialize
90    'charset_aliases' simultaneously, both will produce the same value,
91    and everything will be ok if the two assignments to 'charset_aliases'
92    are atomic. But I don't know what will happen if the two assignments mix.  */
93 #if __STDC__ != 1
94 # define volatile /* empty */
95 #endif
96 /* Pointer to the contents of the charset.alias file, if it has already been
97    read, else NULL.  Its format is:
98    ALIAS_1 '\0' CANONICAL_1 '\0' ... ALIAS_n '\0' CANONICAL_n '\0' '\0'  */
99 static const char * volatile charset_aliases;
100
101 /* Return a pointer to the contents of the charset.alias file.  */
102 static const char *
103 get_charset_aliases (void)
104 {
105   const char *cp;
106
107   cp = charset_aliases;
108   if (cp == NULL)
109     {
110 #if !(defined VMS || defined WIN32_NATIVE || defined __CYGWIN__)
111       FILE *fp;
112       const char *dir;
113       const char *base = "charset.alias";
114       char *file_name;
115
116       /* Make it possible to override the charset.alias location.  This is
117          necessary for running the testsuite before "make install".  */
118       dir = getenv ("CHARSETALIASDIR");
119       if (dir == NULL || dir[0] == '\0')
120         dir = relocate (LIBDIR);
121
122       /* Concatenate dir and base into freshly allocated file_name.  */
123       {
124         size_t dir_len = strlen (dir);
125         size_t base_len = strlen (base);
126         int add_slash = (dir_len > 0 && !ISSLASH (dir[dir_len - 1]));
127         file_name = (char *) malloc (dir_len + add_slash + base_len + 1);
128         if (file_name != NULL)
129           {
130             memcpy (file_name, dir, dir_len);
131             if (add_slash)
132               file_name[dir_len] = DIRECTORY_SEPARATOR;
133             memcpy (file_name + dir_len + add_slash, base, base_len + 1);
134           }
135       }
136
137       if (file_name == NULL || (fp = fopen (file_name, "r")) == NULL)
138         /* Out of memory or file not found, treat it as empty.  */
139         cp = "";
140       else
141         {
142           /* Parse the file's contents.  */
143           char *res_ptr = NULL;
144           size_t res_size = 0;
145
146           for (;;)
147             {
148               int c;
149               char buf1[50+1];
150               char buf2[50+1];
151               size_t l1, l2;
152               char *old_res_ptr;
153
154               c = getc (fp);
155               if (c == EOF)
156                 break;
157               if (c == '\n' || c == ' ' || c == '\t')
158                 continue;
159               if (c == '#')
160                 {
161                   /* Skip comment, to end of line.  */
162                   do
163                     c = getc (fp);
164                   while (!(c == EOF || c == '\n'));
165                   if (c == EOF)
166                     break;
167                   continue;
168                 }
169               ungetc (c, fp);
170               if (fscanf (fp, "%50s %50s", buf1, buf2) < 2)
171                 break;
172               l1 = strlen (buf1);
173               l2 = strlen (buf2);
174               old_res_ptr = res_ptr;
175               if (res_size == 0)
176                 {
177                   res_size = l1 + 1 + l2 + 1;
178                   res_ptr = (char *) malloc (res_size + 1);
179                 }
180               else
181                 {
182                   res_size += l1 + 1 + l2 + 1;
183                   res_ptr = (char *) realloc (res_ptr, res_size + 1);
184                 }
185               if (res_ptr == NULL)
186                 {
187                   /* Out of memory. */
188                   res_size = 0;
189                   if (old_res_ptr != NULL)
190                     free (old_res_ptr);
191                   break;
192                 }
193               strcpy (res_ptr + res_size - (l2 + 1) - (l1 + 1), buf1);
194               strcpy (res_ptr + res_size - (l2 + 1), buf2);
195             }
196           fclose (fp);
197           if (res_size == 0)
198             cp = "";
199           else
200             {
201               *(res_ptr + res_size) = '\0';
202               cp = res_ptr;
203             }
204         }
205
206       if (file_name != NULL)
207         free (file_name);
208
209 #else
210
211 # if defined VMS
212       /* To avoid the troubles of an extra file charset.alias_vms in the
213          sources of many GNU packages, simply inline the aliases here.  */
214       /* The list of encodings is taken from the OpenVMS 7.3-1 documentation
215          "Compaq C Run-Time Library Reference Manual for OpenVMS systems"
216          section 10.7 "Handling Different Character Sets".  */
217       cp = "ISO8859-1" "\0" "ISO-8859-1" "\0"
218            "ISO8859-2" "\0" "ISO-8859-2" "\0"
219            "ISO8859-5" "\0" "ISO-8859-5" "\0"
220            "ISO8859-7" "\0" "ISO-8859-7" "\0"
221            "ISO8859-8" "\0" "ISO-8859-8" "\0"
222            "ISO8859-9" "\0" "ISO-8859-9" "\0"
223            /* Japanese */
224            "eucJP" "\0" "EUC-JP" "\0"
225            "SJIS" "\0" "SHIFT_JIS" "\0"
226            "DECKANJI" "\0" "DEC-KANJI" "\0"
227            "SDECKANJI" "\0" "EUC-JP" "\0"
228            /* Chinese */
229            "eucTW" "\0" "EUC-TW" "\0"
230            "DECHANYU" "\0" "DEC-HANYU" "\0"
231            "DECHANZI" "\0" "GB2312" "\0"
232            /* Korean */
233            "DECKOREAN" "\0" "EUC-KR" "\0";
234 # endif
235
236 # if defined WIN32_NATIVE || defined __CYGWIN__
237       /* To avoid the troubles of installing a separate file in the same
238          directory as the DLL and of retrieving the DLL's directory at
239          runtime, simply inline the aliases here.  */
240
241       cp = "CP936" "\0" "GBK" "\0"
242            "CP1361" "\0" "JOHAB" "\0"
243            "CP20127" "\0" "ASCII" "\0"
244            "CP20866" "\0" "KOI8-R" "\0"
245            "CP20936" "\0" "GB2312" "\0"
246            "CP21866" "\0" "KOI8-RU" "\0"
247            "CP28591" "\0" "ISO-8859-1" "\0"
248            "CP28592" "\0" "ISO-8859-2" "\0"
249            "CP28593" "\0" "ISO-8859-3" "\0"
250            "CP28594" "\0" "ISO-8859-4" "\0"
251            "CP28595" "\0" "ISO-8859-5" "\0"
252            "CP28596" "\0" "ISO-8859-6" "\0"
253            "CP28597" "\0" "ISO-8859-7" "\0"
254            "CP28598" "\0" "ISO-8859-8" "\0"
255            "CP28599" "\0" "ISO-8859-9" "\0"
256            "CP28605" "\0" "ISO-8859-15" "\0"
257            "CP38598" "\0" "ISO-8859-8" "\0"
258            "CP51932" "\0" "EUC-JP" "\0"
259            "CP51936" "\0" "GB2312" "\0"
260            "CP51949" "\0" "EUC-KR" "\0"
261            "CP51950" "\0" "EUC-TW" "\0"
262            "CP54936" "\0" "GB18030" "\0"
263            "CP65001" "\0" "UTF-8" "\0";
264 # endif
265 #endif
266
267       charset_aliases = cp;
268     }
269
270   return cp;
271 }
272
273 /* Determine the current locale's character encoding, and canonicalize it
274    into one of the canonical names listed in config.charset.
275    The result must not be freed; it is statically allocated.
276    If the canonical name cannot be determined, the result is a non-canonical
277    name.  */
278
279 #ifdef STATIC
280 STATIC
281 #endif
282 const char *
283 locale_charset (void)
284 {
285   const char *codeset;
286   const char *aliases;
287
288 #if !(defined WIN32_NATIVE || defined OS2)
289
290 # if HAVE_LANGINFO_CODESET
291
292   /* Most systems support nl_langinfo (CODESET) nowadays.  */
293   codeset = nl_langinfo (CODESET);
294
295 #  ifdef __CYGWIN__
296   /* Cygwin 2006 does not have locales.  nl_langinfo (CODESET) always
297      returns "US-ASCII".  As long as this is not fixed, return the suffix
298      of the locale name from the environment variables (if present) or
299      the codepage as a number.  */
300   if (codeset != NULL && strcmp (codeset, "US-ASCII") == 0)
301     {
302       const char *locale;
303       static char buf[2 + 10 + 1];
304
305       locale = getenv ("LC_ALL");
306       if (locale == NULL || locale[0] == '\0')
307         {
308           locale = getenv ("LC_CTYPE");
309           if (locale == NULL || locale[0] == '\0')
310             locale = getenv ("LANG");
311         }
312       if (locale != NULL && locale[0] != '\0')
313         {
314           /* If the locale name contains an encoding after the dot, return
315              it.  */
316           const char *dot = strchr (locale, '.');
317
318           if (dot != NULL)
319             {
320               const char *modifier;
321
322               dot++;
323               /* Look for the possible @... trailer and remove it, if any.  */
324               modifier = strchr (dot, '@');
325               if (modifier == NULL)
326                 return dot;
327               if (modifier - dot < sizeof (buf))
328                 {
329                   memcpy (buf, dot, modifier - dot);
330                   buf [modifier - dot] = '\0';
331                   return buf;
332                 }
333             }
334         }
335
336       /* Woe32 has a function returning the locale's codepage as a number.  */
337       sprintf (buf, "CP%u", GetACP ());
338       codeset = buf;
339     }
340 #  endif
341
342 # else
343
344   /* On old systems which lack it, use setlocale or getenv.  */
345   const char *locale = NULL;
346
347   /* But most old systems don't have a complete set of locales.  Some
348      (like SunOS 4 or DJGPP) have only the C locale.  Therefore we don't
349      use setlocale here; it would return "C" when it doesn't support the
350      locale name the user has set.  */
351 #  if HAVE_SETLOCALE && 0
352   locale = setlocale (LC_CTYPE, NULL);
353 #  endif
354   if (locale == NULL || locale[0] == '\0')
355     {
356       locale = getenv ("LC_ALL");
357       if (locale == NULL || locale[0] == '\0')
358         {
359           locale = getenv ("LC_CTYPE");
360           if (locale == NULL || locale[0] == '\0')
361             locale = getenv ("LANG");
362         }
363     }
364
365   /* On some old systems, one used to set locale = "iso8859_1". On others,
366      you set it to "language_COUNTRY.charset". In any case, we resolve it
367      through the charset.alias file.  */
368   codeset = locale;
369
370 # endif
371
372 #elif defined WIN32_NATIVE
373
374   static char buf[2 + 10 + 1];
375
376   /* Woe32 has a function returning the locale's codepage as a number.  */
377   sprintf (buf, "CP%u", GetACP ());
378   codeset = buf;
379
380 #elif defined OS2
381
382   const char *locale;
383   static char buf[2 + 10 + 1];
384   ULONG cp[3];
385   ULONG cplen;
386
387   /* Allow user to override the codeset, as set in the operating system,
388      with standard language environment variables.  */
389   locale = getenv ("LC_ALL");
390   if (locale == NULL || locale[0] == '\0')
391     {
392       locale = getenv ("LC_CTYPE");
393       if (locale == NULL || locale[0] == '\0')
394         locale = getenv ("LANG");
395     }
396   if (locale != NULL && locale[0] != '\0')
397     {
398       /* If the locale name contains an encoding after the dot, return it.  */
399       const char *dot = strchr (locale, '.');
400
401       if (dot != NULL)
402         {
403           const char *modifier;
404
405           dot++;
406           /* Look for the possible @... trailer and remove it, if any.  */
407           modifier = strchr (dot, '@');
408           if (modifier == NULL)
409             return dot;
410           if (modifier - dot < sizeof (buf))
411             {
412               memcpy (buf, dot, modifier - dot);
413               buf [modifier - dot] = '\0';
414               return buf;
415             }
416         }
417
418       /* Resolve through the charset.alias file.  */
419       codeset = locale;
420     }
421   else
422     {
423       /* OS/2 has a function returning the locale's codepage as a number.  */
424       if (DosQueryCp (sizeof (cp), cp, &cplen))
425         codeset = "";
426       else
427         {
428           sprintf (buf, "CP%u", cp[0]);
429           codeset = buf;
430         }
431     }
432
433 #endif
434
435   if (codeset == NULL)
436     /* The canonical name cannot be determined.  */
437     codeset = "";
438
439   /* Resolve alias. */
440   for (aliases = get_charset_aliases ();
441        *aliases != '\0';
442        aliases += strlen (aliases) + 1, aliases += strlen (aliases) + 1)
443     if (strcmp (codeset, aliases) == 0
444         || (aliases[0] == '*' && aliases[1] == '\0'))
445       {
446         codeset = aliases + strlen (aliases) + 1;
447         break;
448       }
449
450   /* Don't return an empty string.  GNU libc and GNU libiconv interpret
451      the empty string as denoting "the locale's character encoding",
452      thus GNU libiconv would call this function a second time.  */
453   if (codeset[0] == '\0')
454     codeset = "ASCII";
455
456   return codeset;
457 }