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