Update.
[platform/upstream/glibc.git] / intl / dcgettext.c
1 /* Implementation of the dcgettext(3) function.
2    Copyright (C) 1995, 1996, 1997, 1998, 1999 Free Software Foundation, Inc.
3
4    This file is part of the GNU C Library.  Its master source is NOT part of
5    the C library, however.
6
7    The GNU C Library is free software; you can redistribute it and/or
8    modify it under the terms of the GNU Library General Public License as
9    published by the Free Software Foundation; either version 2 of the
10    License, or (at your option) any later version.
11
12    The GNU C Library is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15    Library General Public License for more details.
16
17    You should have received a copy of the GNU Library General Public
18    License along with the GNU C Library; see the file COPYING.LIB.  If not,
19    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20    Boston, MA 02111-1307, USA.  */
21
22 #ifdef HAVE_CONFIG_H
23 # include <config.h>
24 #endif
25
26 #include <sys/types.h>
27
28 #if defined __GNUC__ && !defined C_ALLOCA
29 # define alloca __builtin_alloca
30 # define HAVE_ALLOCA 1
31 #else
32 # if (defined HAVE_ALLOCA_H || defined _LIBC) && !defined C_ALLOCA
33 #  include <alloca.h>
34 # else
35 #  ifdef _AIX
36  #pragma alloca
37 #  else
38 #   ifndef alloca
39 char *alloca ();
40 #   endif
41 #  endif
42 # endif
43 #endif
44
45 #include <errno.h>
46 #ifndef errno
47 extern int errno;
48 #endif
49 #ifndef __set_errno
50 # define __set_errno(val) errno = (val)
51 #endif
52
53 #if defined STDC_HEADERS || defined _LIBC
54 # include <stdlib.h>
55 #else
56 char *getenv ();
57 # ifdef HAVE_MALLOC_H
58 #  include <malloc.h>
59 # else
60 void free ();
61 # endif
62 #endif
63
64 #if defined HAVE_STRING_H || defined _LIBC
65 # ifndef _GNU_SOURCE
66 #  define _GNU_SOURCE   1
67 # endif
68 # include <string.h>
69 #else
70 # include <strings.h>
71 #endif
72 #if !HAVE_STRCHR && !defined _LIBC
73 # ifndef strchr
74 #  define strchr index
75 # endif
76 #endif
77
78 #if defined HAVE_UNISTD_H || defined _LIBC
79 # include <unistd.h>
80 #endif
81
82 #if defined HAVE_LOCALE_H || defined _LIBC
83 # include <locale.h>
84 #endif
85
86 #if defined HAVE_SYS_PARAM_H || defined _LIBC
87 # include <sys/param.h>
88 #endif
89
90 #include "gettext.h"
91 #include "gettextP.h"
92 #ifdef _LIBC
93 # include <libintl.h>
94 #else
95 # include "libgettext.h"
96 #endif
97 #include "hash-string.h"
98
99 /* Thread safetyness.  */
100 #ifdef _LIBC
101 # include <bits/libc-lock.h>
102 #endif
103
104 /* @@ end of prolog @@ */
105
106 #ifdef _LIBC
107 /* Rename the non ANSI C functions.  This is required by the standard
108    because some ANSI C functions will require linking with this object
109    file and the name space must not be polluted.  */
110 # define getcwd __getcwd
111 # ifndef stpcpy
112 #  define stpcpy __stpcpy
113 # endif
114 #else
115 # if !defined HAVE_GETCWD
116 char *getwd ();
117 #  define getcwd(buf, max) getwd (buf)
118 # else
119 char *getcwd ();
120 # endif
121 # ifndef HAVE_STPCPY
122 static char *stpcpy PARAMS ((char *dest, const char *src));
123 # endif
124 #endif
125
126 /* Amount to increase buffer size by in each try.  */
127 #define PATH_INCR 32
128
129 /* The following is from pathmax.h.  */
130 /* Non-POSIX BSD systems might have gcc's limits.h, which doesn't define
131    PATH_MAX but might cause redefinition warnings when sys/param.h is
132    later included (as on MORE/BSD 4.3).  */
133 #if defined(_POSIX_VERSION) || (defined(HAVE_LIMITS_H) && !defined(__GNUC__))
134 # include <limits.h>
135 #endif
136
137 #ifndef _POSIX_PATH_MAX
138 # define _POSIX_PATH_MAX 255
139 #endif
140
141 #if !defined(PATH_MAX) && defined(_PC_PATH_MAX)
142 # define PATH_MAX (pathconf ("/", _PC_PATH_MAX) < 1 ? 1024 : pathconf ("/", _PC_PATH_MAX))
143 #endif
144
145 /* Don't include sys/param.h if it already has been.  */
146 #if defined(HAVE_SYS_PARAM_H) && !defined(PATH_MAX) && !defined(MAXPATHLEN)
147 # include <sys/param.h>
148 #endif
149
150 #if !defined(PATH_MAX) && defined(MAXPATHLEN)
151 # define PATH_MAX MAXPATHLEN
152 #endif
153
154 #ifndef PATH_MAX
155 # define PATH_MAX _POSIX_PATH_MAX
156 #endif
157
158 /* XPG3 defines the result of `setlocale (category, NULL)' as:
159    ``Directs `setlocale()' to query `category' and return the current
160      setting of `local'.''
161    However it does not specify the exact format.  And even worse: POSIX
162    defines this not at all.  So we can use this feature only on selected
163    system (e.g. those using GNU C Library).  */
164 #ifdef _LIBC
165 # define HAVE_LOCALE_NULL
166 #endif
167
168 /* Name of the default domain used for gettext(3) prior any call to
169    textdomain(3).  The default value for this is "messages".  */
170 const char _nl_default_default_domain[] = "messages";
171
172 /* Value used as the default domain for gettext(3).  */
173 const char *_nl_current_default_domain = _nl_default_default_domain;
174
175 /* Contains the default location of the message catalogs.  */
176 const char _nl_default_dirname[] = GNULOCALEDIR;
177
178 /* List with bindings of specific domains created by bindtextdomain()
179    calls.  */
180 struct binding *_nl_domain_bindings;
181
182 /* Prototypes for local functions.  */
183 static const char *category_to_name PARAMS ((int category)) internal_function;
184 static const char *guess_category_value PARAMS ((int category,
185                                                  const char *categoryname))
186      internal_function;
187
188
189 /* For those loosing systems which don't have `alloca' we have to add
190    some additional code emulating it.  */
191 #ifdef HAVE_ALLOCA
192 /* Nothing has to be done.  */
193 # define ADD_BLOCK(list, address) /* nothing */
194 # define FREE_BLOCKS(list) /* nothing */
195 #else
196 struct block_list
197 {
198   void *address;
199   struct block_list *next;
200 };
201 # define ADD_BLOCK(list, addr)                                                \
202   do {                                                                        \
203     struct block_list *newp = (struct block_list *) malloc (sizeof (*newp));  \
204     /* If we cannot get a free block we cannot add the new element to         \
205        the list.  */                                                          \
206     if (newp != NULL) {                                                       \
207       newp->address = (addr);                                                 \
208       newp->next = (list);                                                    \
209       (list) = newp;                                                          \
210     }                                                                         \
211   } while (0)
212 # define FREE_BLOCKS(list)                                                    \
213   do {                                                                        \
214     while (list != NULL) {                                                    \
215       struct block_list *old = list;                                          \
216       list = list->next;                                                      \
217       free (old);                                                             \
218     }                                                                         \
219   } while (0)
220 # undef alloca
221 # define alloca(size) (malloc (size))
222 #endif  /* have alloca */
223
224
225 /* Names for the libintl functions are a problem.  They must not clash
226    with existing names and they should follow ANSI C.  But this source
227    code is also used in GNU C Library where the names have a __
228    prefix.  So we have to make a difference here.  */
229 #ifdef _LIBC
230 # define DCGETTEXT __dcgettext
231 #else
232 # define DCGETTEXT dcgettext__
233 #endif
234
235 /* Checking whether the binaries runs SUID must be done and glibc provides
236    easier methods therefore we make a difference here.  */
237 #ifdef _LIBC
238 # define ENABLE_SECURE __libc_enable_secure
239 # define DETERMINE_SECURE
240 #else
241 static int enable_secure;
242 # define ENABLE_SECURE (enable_secure == 1)
243 # define DETERMINE_SECURE \
244   if (enable_secure == 0)                                                     \
245     {                                                                         \
246       if (getuid () != geteuid () || getgid () != getegid ())                 \
247         enable_secure = 1;                                                    \
248       else                                                                    \
249         enable_secure = -1;                                                   \
250     }
251 #endif
252
253 /* Look up MSGID in the DOMAINNAME message catalog for the current CATEGORY
254    locale.  */
255 char *
256 DCGETTEXT (domainname, msgid, category)
257      const char *domainname;
258      const char *msgid;
259      int category;
260 {
261 #ifndef HAVE_ALLOCA
262   struct block_list *block_list = NULL;
263 #endif
264   struct loaded_l10nfile *domain;
265   struct binding *binding;
266   const char *categoryname;
267   const char *categoryvalue;
268   char *dirname, *xdomainname;
269   char *single_locale;
270   char *retval;
271   int saved_errno = errno;
272
273   /* If no real MSGID is given return NULL.  */
274   if (msgid == NULL)
275     return NULL;
276
277   /* See whether this is a SUID binary or not.  */
278   DETERMINE_SECURE;
279
280   /* If DOMAINNAME is NULL, we are interested in the default domain.  If
281      CATEGORY is not LC_MESSAGES this might not make much sense but the
282      definition left this undefined.  */
283   if (domainname == NULL)
284     domainname = _nl_current_default_domain;
285
286   /* First find matching binding.  */
287   for (binding = _nl_domain_bindings; binding != NULL; binding = binding->next)
288     {
289       int compare = strcmp (domainname, binding->domainname);
290       if (compare == 0)
291         /* We found it!  */
292         break;
293       if (compare < 0)
294         {
295           /* It is not in the list.  */
296           binding = NULL;
297           break;
298         }
299     }
300
301   if (binding == NULL)
302     dirname = (char *) _nl_default_dirname;
303   else if (binding->dirname[0] == '/')
304     dirname = binding->dirname;
305   else
306     {
307       /* We have a relative path.  Make it absolute now.  */
308       size_t dirname_len = strlen (binding->dirname) + 1;
309       size_t path_max;
310       char *ret;
311
312       path_max = (unsigned int) PATH_MAX;
313       path_max += 2;            /* The getcwd docs say to do this.  */
314
315       dirname = (char *) alloca (path_max + dirname_len);
316       ADD_BLOCK (block_list, dirname);
317
318       __set_errno (0);
319       while ((ret = getcwd (dirname, path_max)) == NULL && errno == ERANGE)
320         {
321           path_max += PATH_INCR;
322           dirname = (char *) alloca (path_max + dirname_len);
323           ADD_BLOCK (block_list, dirname);
324           __set_errno (0);
325         }
326
327       if (ret == NULL)
328         {
329           /* We cannot get the current working directory.  Don't signal an
330              error but simply return the default string.  */
331           FREE_BLOCKS (block_list);
332           __set_errno (saved_errno);
333           return (char *) msgid;
334         }
335
336       stpcpy (stpcpy (strchr (dirname, '\0'), "/"), binding->dirname);
337     }
338
339   /* Now determine the symbolic name of CATEGORY and its value.  */
340   categoryname = category_to_name (category);
341   categoryvalue = guess_category_value (category, categoryname);
342
343   xdomainname = (char *) alloca (strlen (categoryname)
344                                  + strlen (domainname) + 5);
345   ADD_BLOCK (block_list, xdomainname);
346
347   stpcpy (stpcpy (stpcpy (stpcpy (xdomainname, categoryname), "/"),
348                   domainname),
349           ".mo");
350
351   /* Creating working area.  */
352   single_locale = (char *) alloca (strlen (categoryvalue) + 1);
353   ADD_BLOCK (block_list, single_locale);
354
355
356   /* Search for the given string.  This is a loop because we perhaps
357      got an ordered list of languages to consider for the translation.  */
358   while (1)
359     {
360       /* Make CATEGORYVALUE point to the next element of the list.  */
361       while (categoryvalue[0] != '\0' && categoryvalue[0] == ':')
362         ++categoryvalue;
363       if (categoryvalue[0] == '\0')
364         {
365           /* The whole contents of CATEGORYVALUE has been searched but
366              no valid entry has been found.  We solve this situation
367              by implicitly appending a "C" entry, i.e. no translation
368              will take place.  */
369           single_locale[0] = 'C';
370           single_locale[1] = '\0';
371         }
372       else
373         {
374           char *cp = single_locale;
375           while (categoryvalue[0] != '\0' && categoryvalue[0] != ':')
376             *cp++ = *categoryvalue++;
377           *cp = '\0';
378
379           /* When this is a SUID binary we must not allow accessing files
380              outside the dedicated directories.  */
381           if (ENABLE_SECURE
382               && (memchr (single_locale, '/',
383                           _nl_find_language (single_locale) - single_locale)
384                   != NULL))
385             /* Ingore this entry.  */
386             continue;
387         }
388
389       /* If the current locale value is C (or POSIX) we don't load a
390          domain.  Return the MSGID.  */
391       if (strcmp (single_locale, "C") == 0
392           || strcmp (single_locale, "POSIX") == 0)
393         {
394           FREE_BLOCKS (block_list);
395           __set_errno (saved_errno);
396           return (char *) msgid;
397         }
398
399
400       /* Find structure describing the message catalog matching the
401          DOMAINNAME and CATEGORY.  */
402       domain = _nl_find_domain (dirname, single_locale, xdomainname);
403
404       if (domain != NULL)
405         {
406           retval = _nl_find_msg (domain, msgid);
407
408           if (retval == NULL)
409             {
410               int cnt;
411
412               for (cnt = 0; domain->successor[cnt] != NULL; ++cnt)
413                 {
414                   retval = _nl_find_msg (domain->successor[cnt], msgid);
415
416                   if (retval != NULL)
417                     break;
418                 }
419             }
420
421           if (retval != NULL)
422             {
423               FREE_BLOCKS (block_list);
424               __set_errno (saved_errno);
425               return retval;
426             }
427         }
428     }
429   /* NOTREACHED */
430 }
431
432 #ifdef _LIBC
433 /* Alias for function name in GNU C Library.  */
434 weak_alias (__dcgettext, dcgettext);
435 #endif
436
437
438 char *
439 internal_function
440 _nl_find_msg (domain_file, msgid)
441      struct loaded_l10nfile *domain_file;
442      const char *msgid;
443 {
444   size_t act = 0;
445   size_t top, bottom;
446   struct loaded_domain *domain;
447
448   if (domain_file->decided == 0)
449     _nl_load_domain (domain_file);
450
451   if (domain_file->data == NULL)
452     return NULL;
453
454   domain = (struct loaded_domain *) domain_file->data;
455
456   /* Locate the MSGID and its translation.  */
457   if (domain->hash_size > 2 && domain->hash_tab != NULL)
458     {
459       /* Use the hashing table.  */
460       nls_uint32 len = strlen (msgid);
461       nls_uint32 hash_val = hash_string (msgid);
462       nls_uint32 idx = hash_val % domain->hash_size;
463       nls_uint32 incr = 1 + (hash_val % (domain->hash_size - 2));
464       nls_uint32 nstr = W (domain->must_swap, domain->hash_tab[idx]);
465
466       if (nstr == 0)
467         /* Hash table entry is empty.  */
468         return NULL;
469
470       if (W (domain->must_swap, domain->orig_tab[nstr - 1].length) == len
471           && strcmp (msgid,
472                      domain->data + W (domain->must_swap,
473                                        domain->orig_tab[nstr - 1].offset)) == 0)
474         {
475           /* We found an entry.  If we have to convert the string to use
476              a different character set this is the time.  */
477           char *result =
478             (char *) domain->data + W (domain->must_swap,
479                                        domain->trans_tab[nstr - 1].offset);
480
481           if (
482 #if HAVE_ICONV || defined _LIBC
483               domain->conv != (iconv_t) -1
484 #endif
485               )
486             {
487               /* We are supposed to do a conversion.  First allocate an
488                  appropriate table with the same structure as the hash
489                  table in the file where we can put the pointers to the
490                  converted strings in.  */
491               if (domain->conv_tab == NULL
492                   && ((domain->conv_tab = (char **) calloc (domain->hash_size,
493                                                             sizeof (char *)))
494                       == NULL))
495                 /* Mark that we didn't succeed allocating a table.  */
496                 domain->conv_tab = (char **) -1;
497
498               if (domain->conv_tab == (char **) -1)
499                 /* Nothing we can do, no more memory.  */
500                 return NULL;
501
502               if (domain->conv_tab[idx] == NULL)
503                 {
504                   /* We haven't used this string so far, so it is not
505                      translated yet.  Do this now.  */
506 #ifdef _LIBC
507                   /* For glibc we use a bit more efficient memory handling.
508                      We allocate always larger blocks which get used over
509                      time.  This is faster than many small allocations.   */
510                   __libc_lock_define_initialized (static, lock)
511                   static char *freemem;
512                   static size_t freemem_size;
513                   /* Note that we include the NUL byte.  */
514                   size_t resultlen = strlen (result) + 1;
515                   const char *inbuf = result;
516                   size_t inbytesleft = resultlen;
517                   char *outbuf = freemem;
518                   size_t outbytesleft = freemem_size;
519
520                   __libc_lock_lock (lock);
521
522                   while (iconv (domain->conv, &inbuf, &inbytesleft, &outbuf,
523                                 &outbytesleft) == (size_t) -1L)
524                     {
525                       if (errno != E2BIG)
526                         goto out;
527
528                       /* We must resize the buffer.  */
529                       freemem_size = MAX (2 * freemem_size, 4064);
530                       freemem = (char *) malloc (freemem_size);
531                       if (freemem == NULL)
532                         goto out;
533
534                       inbuf = result;
535                       inbytesleft = resultlen;
536                       outbuf = freemem;
537                       outbytesleft = freemem_size;
538                     }
539
540                   /* We have now in our buffer a converted string.  Put this
541                      in the hash table  */
542                   domain->conv_tab[idx] = freemem;
543                   freemem = outbuf;
544                   freemem_size = outbytesleft;
545
546                 out:
547                   __libc_lock_unlock (lock);
548 #endif
549                 }
550
551               result = domain->conv_tab[idx];
552             }
553
554           return result;
555         }
556
557       while (1)
558         {
559           if (idx >= domain->hash_size - incr)
560             idx -= domain->hash_size - incr;
561           else
562             idx += incr;
563
564           nstr = W (domain->must_swap, domain->hash_tab[idx]);
565           if (nstr == 0)
566             /* Hash table entry is empty.  */
567             return NULL;
568
569           if (W (domain->must_swap, domain->orig_tab[nstr - 1].length) == len
570               && strcmp (msgid,
571                          domain->data + W (domain->must_swap,
572                                            domain->orig_tab[nstr - 1].offset))
573                  == 0)
574             return (char *) domain->data
575               + W (domain->must_swap, domain->trans_tab[nstr - 1].offset);
576         }
577       /* NOTREACHED */
578     }
579
580   /* Now we try the default method:  binary search in the sorted
581      array of messages.  */
582   bottom = 0;
583   top = domain->nstrings;
584   while (bottom < top)
585     {
586       int cmp_val;
587
588       act = (bottom + top) / 2;
589       cmp_val = strcmp (msgid, domain->data
590                                + W (domain->must_swap,
591                                     domain->orig_tab[act].offset));
592       if (cmp_val < 0)
593         top = act;
594       else if (cmp_val > 0)
595         bottom = act + 1;
596       else
597         break;
598     }
599
600   /* If an translation is found return this.  */
601   return bottom >= top ? NULL : (char *) domain->data
602                                 + W (domain->must_swap,
603                                      domain->trans_tab[act].offset);
604 }
605
606
607 /* Return string representation of locale CATEGORY.  */
608 static const char *
609 internal_function
610 category_to_name (category)
611      int category;
612 {
613   const char *retval;
614
615   switch (category)
616   {
617 #ifdef LC_COLLATE
618   case LC_COLLATE:
619     retval = "LC_COLLATE";
620     break;
621 #endif
622 #ifdef LC_CTYPE
623   case LC_CTYPE:
624     retval = "LC_CTYPE";
625     break;
626 #endif
627 #ifdef LC_MONETARY
628   case LC_MONETARY:
629     retval = "LC_MONETARY";
630     break;
631 #endif
632 #ifdef LC_NUMERIC
633   case LC_NUMERIC:
634     retval = "LC_NUMERIC";
635     break;
636 #endif
637 #ifdef LC_TIME
638   case LC_TIME:
639     retval = "LC_TIME";
640     break;
641 #endif
642 #ifdef LC_MESSAGES
643   case LC_MESSAGES:
644     retval = "LC_MESSAGES";
645     break;
646 #endif
647 #ifdef LC_RESPONSE
648   case LC_RESPONSE:
649     retval = "LC_RESPONSE";
650     break;
651 #endif
652 #ifdef LC_ALL
653   case LC_ALL:
654     /* This might not make sense but is perhaps better than any other
655        value.  */
656     retval = "LC_ALL";
657     break;
658 #endif
659   default:
660     /* If you have a better idea for a default value let me know.  */
661     retval = "LC_XXX";
662   }
663
664   return retval;
665 }
666
667 /* Guess value of current locale from value of the environment variables.  */
668 static const char *
669 internal_function
670 guess_category_value (category, categoryname)
671      int category;
672      const char *categoryname;
673 {
674   const char *retval;
675
676   /* The highest priority value is the `LANGUAGE' environment
677      variable.  This is a GNU extension.  */
678   retval = getenv ("LANGUAGE");
679   if (retval != NULL && retval[0] != '\0')
680     return retval;
681
682   /* `LANGUAGE' is not set.  So we have to proceed with the POSIX
683      methods of looking to `LC_ALL', `LC_xxx', and `LANG'.  On some
684      systems this can be done by the `setlocale' function itself.  */
685 #if defined HAVE_SETLOCALE && defined HAVE_LC_MESSAGES && defined HAVE_LOCALE_NULL
686   return setlocale (category, NULL);
687 #else
688   /* Setting of LC_ALL overwrites all other.  */
689   retval = getenv ("LC_ALL");
690   if (retval != NULL && retval[0] != '\0')
691     return retval;
692
693   /* Next comes the name of the desired category.  */
694   retval = getenv (categoryname);
695   if (retval != NULL && retval[0] != '\0')
696     return retval;
697
698   /* Last possibility is the LANG environment variable.  */
699   retval = getenv ("LANG");
700   if (retval != NULL && retval[0] != '\0')
701     return retval;
702
703   /* We use C as the default domain.  POSIX says this is implementation
704      defined.  */
705   return "C";
706 #endif
707 }
708
709 /* @@ begin of epilog @@ */
710
711 /* We don't want libintl.a to depend on any other library.  So we
712    avoid the non-standard function stpcpy.  In GNU C Library this
713    function is available, though.  Also allow the symbol HAVE_STPCPY
714    to be defined.  */
715 #if !_LIBC && !HAVE_STPCPY
716 static char *
717 stpcpy (dest, src)
718      char *dest;
719      const char *src;
720 {
721   while ((*dest++ = *src++) != '\0')
722     /* Do nothing. */ ;
723   return dest - 1;
724 }
725 #endif
726
727
728 #ifdef _LIBC
729 /* If we want to free all resources we have to do some work at
730    program's end.  */
731 static void __attribute__ ((unused))
732 free_mem (void)
733 {
734   struct binding *runp;
735
736   for (runp = _nl_domain_bindings; runp != NULL; runp = runp->next)
737     {
738       free (runp->domainname);
739       if (runp->dirname != _nl_default_dirname)
740         /* Yes, this is a pointer comparison.  */
741         free (runp->dirname);
742     }
743
744   if (_nl_current_default_domain != _nl_default_default_domain)
745     /* Yes, again a pointer comparison.  */
746     free ((char *) _nl_current_default_domain);
747 }
748
749 text_set_element (__libc_subfreeres, free_mem);
750 #endif