Match also UNC paths on Win32.
[platform/upstream/glib.git] / gutils.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1998  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library 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 GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 /* 
28  * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #include <config.h>
33 #endif
34
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38 #include <stdarg.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <errno.h>
43 #ifdef HAVE_PWD_H
44 #include <pwd.h>
45 #endif
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_PARAM_H
48 #include <sys/param.h>
49 #endif
50
51 /* implement Glib's inline functions
52  */
53 #define G_IMPLEMENT_INLINES 1
54 #define __G_UTILS_C__
55 #include "glib.h"
56
57 #ifdef  MAXPATHLEN
58 #define G_PATH_LENGTH   MAXPATHLEN
59 #elif   defined (PATH_MAX)
60 #define G_PATH_LENGTH   PATH_MAX
61 #elif   defined (_PC_PATH_MAX)
62 #define G_PATH_LENGTH   sysconf(_PC_PATH_MAX)
63 #else   
64 #define G_PATH_LENGTH   2048
65 #endif
66
67 #ifdef G_OS_WIN32
68 #  define STRICT                        /* Strict typing, please */
69 #  include <windows.h>
70 #  include <ctype.h>
71 #  include <direct.h>
72 #endif /* G_OS_WIN32 */
73
74 #ifdef HAVE_CODESET
75 #include <langinfo.h>
76 #endif
77
78 const guint glib_major_version = GLIB_MAJOR_VERSION;
79 const guint glib_minor_version = GLIB_MINOR_VERSION;
80 const guint glib_micro_version = GLIB_MICRO_VERSION;
81 const guint glib_interface_age = GLIB_INTERFACE_AGE;
82 const guint glib_binary_age = GLIB_BINARY_AGE;
83
84 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
85 void 
86 g_memmove (gpointer dest, gconstpointer src, gulong len)
87 {
88   gchar* destptr = dest;
89   const gchar* srcptr = src;
90   if (src + len < dest || dest + len < src)
91     {
92       bcopy (src, dest, len);
93       return;
94     }
95   else if (dest <= src)
96     {
97       while (len--)
98         *(destptr++) = *(srcptr++);
99     }
100   else
101     {
102       destptr += len;
103       srcptr += len;
104       while (len--)
105         *(--destptr) = *(--srcptr);
106     }
107 }
108 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
109
110 void
111 g_atexit (GVoidFunc func)
112 {
113   gint result;
114   const gchar *error = NULL;
115
116   /* keep this in sync with glib.h */
117
118 #ifdef  G_NATIVE_ATEXIT
119   result = ATEXIT (func);
120   if (result)
121     error = g_strerror (errno);
122 #elif defined (HAVE_ATEXIT)
123 #  ifdef NeXT /* @#%@! NeXTStep */
124   result = !atexit ((void (*)(void)) func);
125   if (result)
126     error = g_strerror (errno);
127 #  else
128   result = atexit ((void (*)(void)) func);
129   if (result)
130     error = g_strerror (errno);
131 #  endif /* NeXT */
132 #elif defined (HAVE_ON_EXIT)
133   result = on_exit ((void (*)(int, void *)) func, NULL);
134   if (result)
135     error = g_strerror (errno);
136 #else
137   result = 0;
138   error = "no implementation";
139 #endif /* G_NATIVE_ATEXIT */
140
141   if (error)
142     g_error ("Could not register atexit() function: %s", error);
143 }
144
145 /* Based on execvp() from GNU Libc.
146  * Some of this code is cut-and-pasted into gspawn.c
147  */
148
149 static gchar*
150 my_strchrnul (const gchar *str, gchar c)
151 {
152   gchar *p = (gchar*)str;
153   while (*p && (*p != c))
154     ++p;
155
156   return p;
157 }
158
159 /**
160  * g_find_program_in_path:
161  * @program: a program name
162  * 
163  * Locates the first executable named @program in the user's path, in the
164  * same way that execvp() would locate it. Returns an allocated string
165  * with the absolute path name, or NULL if the program is not found in
166  * the path. If @program is already an absolute path, returns a copy of
167  * @program if @program exists and is executable, and NULL otherwise.
168  * 
169  * Return value: absolute path, or NULL
170  **/
171 gchar*
172 g_find_program_in_path (const gchar *program)
173 {
174   const gchar *path, *p;
175   gchar *name, *freeme;
176   size_t len;
177   size_t pathlen;
178
179   g_return_val_if_fail (program != NULL, NULL);
180
181   if (*program == '/')
182     {
183       if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE))
184         return g_strdup (program);
185       else
186         return NULL;
187     }
188   
189   path = g_getenv ("PATH");
190   if (path == NULL)
191     {
192       /* There is no `PATH' in the environment.  The default
193        * search path in GNU libc is the current directory followed by
194        * the path `confstr' returns for `_CS_PATH'.
195        */
196       
197       /* In GLib we put . last, for security, and don't use the
198        * unportable confstr(); UNIX98 does not actually specify
199        * what to search if PATH is unset. POSIX may, dunno.
200        */
201       
202       path = "/bin:/usr/bin:.";
203     }
204   
205   len = strlen (program) + 1;
206   pathlen = strlen (path);
207   freeme = name = g_malloc (pathlen + len + 1);
208   
209   /* Copy the file name at the top, including '\0'  */
210   memcpy (name + pathlen + 1, program, len);
211   name = name + pathlen;
212   /* And add the slash before the filename  */
213   *name = '/';
214   
215   p = path;
216   do
217     {
218       char *startp;
219
220       path = p;
221       p = my_strchrnul (path, ':');
222
223       if (p == path)
224         /* Two adjacent colons, or a colon at the beginning or the end
225          * of `PATH' means to search the current directory.
226          */
227         startp = name + 1;
228       else
229         startp = memcpy (name - (p - path), path, p - path);
230
231       if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE))
232         {
233           gchar *ret;
234           ret = g_strdup (startp);
235           g_free (freeme);
236           return ret;
237         }
238     }
239   while (*p++ != '\0');
240   
241   g_free (freeme);
242
243   return NULL;
244 }
245
246 gint
247 g_snprintf (gchar       *str,
248             gulong       n,
249             gchar const *fmt,
250             ...)
251 {
252 #ifdef  HAVE_VSNPRINTF
253   va_list args;
254   gint retval;
255   
256   g_return_val_if_fail (str != NULL, 0);
257   g_return_val_if_fail (n > 0, 0);
258   g_return_val_if_fail (fmt != NULL, 0);
259
260   va_start (args, fmt);
261   retval = vsnprintf (str, n, fmt, args);
262   va_end (args);
263
264   if (retval < 0)
265     {
266       str[n-1] = '\0';
267       retval = strlen (str);
268     }
269
270   return retval;
271 #else   /* !HAVE_VSNPRINTF */
272   gchar *printed;
273   va_list args;
274   
275   g_return_val_if_fail (str != NULL, 0);
276   g_return_val_if_fail (n > 0, 0);
277   g_return_val_if_fail (fmt != NULL, 0);
278
279   va_start (args, fmt);
280   printed = g_strdup_vprintf (fmt, args);
281   va_end (args);
282   
283   strncpy (str, printed, n);
284   str[n-1] = '\0';
285
286   g_free (printed);
287   
288   return strlen (str);
289 #endif  /* !HAVE_VSNPRINTF */
290 }
291
292 gint
293 g_vsnprintf (gchar       *str,
294              gulong       n,
295              gchar const *fmt,
296              va_list      args)
297 {
298 #ifdef  HAVE_VSNPRINTF
299   gint retval;
300   
301   g_return_val_if_fail (str != NULL, 0);
302   g_return_val_if_fail (n > 0, 0);
303   g_return_val_if_fail (fmt != NULL, 0);
304
305   retval = vsnprintf (str, n, fmt, args);
306   
307   if (retval < 0)
308     {
309       str[n-1] = '\0';
310       retval = strlen (str);
311     }
312
313   return retval;
314 #else   /* !HAVE_VSNPRINTF */
315   gchar *printed;
316   
317   g_return_val_if_fail (str != NULL, 0);
318   g_return_val_if_fail (n > 0, 0);
319   g_return_val_if_fail (fmt != NULL, 0);
320
321   printed = g_strdup_vprintf (fmt, args);
322   strncpy (str, printed, n);
323   str[n-1] = '\0';
324
325   g_free (printed);
326   
327   return strlen (str);
328 #endif /* !HAVE_VSNPRINTF */
329 }
330
331 guint        
332 g_parse_debug_string  (const gchar *string, 
333                        GDebugKey   *keys, 
334                        guint        nkeys)
335 {
336   guint i;
337   guint result = 0;
338   
339   g_return_val_if_fail (string != NULL, 0);
340   
341   if (!g_strcasecmp (string, "all"))
342     {
343       for (i=0; i<nkeys; i++)
344         result |= keys[i].value;
345     }
346   else
347     {
348       gchar *str = g_strdup (string);
349       gchar *p = str;
350       gchar *q;
351       gboolean done = FALSE;
352       
353       while (*p && !done)
354         {
355           q = strchr (p, ':');
356           if (!q)
357             {
358               q = p + strlen(p);
359               done = TRUE;
360             }
361           
362           *q = 0;
363           
364           for (i=0; i<nkeys; i++)
365             if (!g_strcasecmp(keys[i].key, p))
366               result |= keys[i].value;
367           
368           p = q+1;
369         }
370       
371       g_free (str);
372     }
373   
374   return result;
375 }
376
377 G_CONST_RETURN gchar*
378 g_basename (const gchar    *file_name)
379 {
380   register gchar *base;
381 #if defined(G_ENABLE_DEBUG) && !defined(G_OS_WIN32)
382   static gboolean first_call = TRUE;
383
384   if (first_call)
385     {
386       g_message ("g_basename is deprecated. Use g_path_get_basename instead. "
387                  "Beware that the string returned by g_path_get_basename() has "
388                  " to be g_free()ed.");
389       first_call = FALSE;
390     }
391 #endif /* G_ENABLE_DEBUG */
392   
393   g_return_val_if_fail (file_name != NULL, NULL);
394   
395   base = strrchr (file_name, G_DIR_SEPARATOR);
396   if (base)
397     return base + 1;
398
399 #ifdef G_OS_WIN32
400   if (isalpha (file_name[0]) && file_name[1] == ':')
401     return (gchar*) file_name + 2;
402 #endif /* G_OS_WIN32 */
403   
404   return (gchar*) file_name;
405 }
406
407 gchar*
408 g_path_get_basename (const gchar   *file_name)
409 {
410   register gint base;
411   register gint last_nonslash;
412   guint len;
413   gchar *retval;
414  
415   g_return_val_if_fail (file_name != NULL, NULL);
416   
417   if (file_name[0] == '\0')
418     /* empty string */
419     return g_strdup (".");
420
421   last_nonslash = strlen (file_name) - 1;
422
423   while (last_nonslash >= 0 && file_name [last_nonslash] == G_DIR_SEPARATOR)
424     last_nonslash--;
425
426   if (last_nonslash == -1)
427     /* string only containing slashes */
428     return g_strdup (G_DIR_SEPARATOR_S);
429
430 #ifdef G_OS_WIN32
431   if (last_nonslash == 1 && isalpha (file_name[0]) && file_name[1] == ':')
432     /* string only containing slashes and a drive */
433     return g_strdup (G_DIR_SEPARATOR_S);
434 #endif /* G_OS_WIN32 */
435
436   base = last_nonslash;
437
438   while (base >=0 && file_name [base] != G_DIR_SEPARATOR)
439     base--;
440
441 #ifdef G_OS_WIN32
442   if (base == -1 && isalpha (file_name[0]) && file_name[1] == ':')
443     base = 1;
444 #endif /* G_OS_WIN32 */
445
446   len = last_nonslash - base;
447   retval = g_malloc (len + 1);
448   memcpy (retval, file_name + base + 1, len);
449   retval [len] = '\0';
450   return retval;
451 }
452
453 gboolean
454 g_path_is_absolute (const gchar *file_name)
455 {
456   g_return_val_if_fail (file_name != NULL, FALSE);
457   
458   if (file_name[0] == G_DIR_SEPARATOR)
459     return TRUE;
460
461 #ifdef G_OS_WIN32
462   if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
463     return TRUE;
464
465   if (file_name[0] == G_DIR_SEPARATOR && file_name[1] == G_DIR_SEPARATOR)
466     return TRUE;
467 #endif
468
469   return FALSE;
470 }
471
472 G_CONST_RETURN gchar*
473 g_path_skip_root (const gchar *file_name)
474 {
475   g_return_val_if_fail (file_name != NULL, NULL);
476   
477 #ifdef G_OS_WIN32
478   /* Skip \\server\share */
479   if (file_name[0] == G_DIR_SEPARATOR &&
480       file_name[1] == G_DIR_SEPARATOR &&
481       file_name[2])
482     {
483       gchar *p, *q;
484
485       if ((p = strchr (file_name + 2, G_DIR_SEPARATOR)) > file_name + 2 &&
486           p[1])
487         {
488           file_name = p + 1;
489
490           while (file_name[0] && file_name[0] != G_DIR_SEPARATOR)
491             file_name++;
492
493           /* Possibly skip a backslash after the share name */
494           if (file_name[0] == G_DIR_SEPARATOR)
495             file_name++;
496
497           return (gchar *)file_name;
498         }
499     }
500 #endif
501   
502   /* Skip initial slashes */
503   if (file_name[0] == G_DIR_SEPARATOR)
504     {
505       while (file_name[0] == G_DIR_SEPARATOR)
506         file_name++;
507       return (gchar *)file_name;
508     }
509
510 #ifdef G_OS_WIN32
511   /* Skip X:\ */
512   if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
513     return (gchar *)file_name + 3;
514 #endif
515
516   return NULL;
517 }
518
519 gchar*
520 g_path_get_dirname (const gchar    *file_name)
521 {
522   register gchar *base;
523   register guint len;
524   
525   g_return_val_if_fail (file_name != NULL, NULL);
526   
527   base = strrchr (file_name, G_DIR_SEPARATOR);
528   if (!base)
529     return g_strdup (".");
530   while (base > file_name && *base == G_DIR_SEPARATOR)
531     base--;
532   len = (guint) 1 + base - file_name;
533   
534   base = g_new (gchar, len + 1);
535   g_memmove (base, file_name, len);
536   base[len] = 0;
537   
538   return base;
539 }
540
541 gchar*
542 g_dirname (const gchar     *file_name)
543 {
544 #if defined(G_ENABLE_DEBUG) && !defined(G_OS_WIN32)
545   static gboolean first_call = TRUE;
546
547   if (first_call)
548     {
549       g_message ("g_dirname() is deprecated. Use g_path_get_dirname() instead.");
550       first_call = FALSE;
551     }
552 #endif /* G_ENABLE_DEBUG */
553
554   return g_path_get_dirname (file_name);
555 }
556
557 gchar*
558 g_get_current_dir (void)
559 {
560   gchar *buffer = NULL;
561   gchar *dir = NULL;
562   static gulong max_len = 0;
563
564   if (max_len == 0) 
565     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
566   
567   /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
568    * and, if that wasn't bad enough, hangs in doing so.
569    */
570 #if     (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
571   buffer = g_new (gchar, max_len + 1);
572   *buffer = 0;
573   dir = getwd (buffer);
574 #else   /* !sun || !HAVE_GETCWD */
575   while (max_len < G_MAXULONG / 2)
576     {
577       buffer = g_new (gchar, max_len + 1);
578       *buffer = 0;
579       dir = getcwd (buffer, max_len);
580
581       if (dir || errno != ERANGE)
582         break;
583
584       g_free (buffer);
585       max_len *= 2;
586     }
587 #endif  /* !sun || !HAVE_GETCWD */
588   
589   if (!dir || !*buffer)
590     {
591       /* hm, should we g_error() out here?
592        * this can happen if e.g. "./" has mode \0000
593        */
594       buffer[0] = G_DIR_SEPARATOR;
595       buffer[1] = 0;
596     }
597
598   dir = g_strdup (buffer);
599   g_free (buffer);
600   
601   return dir;
602 }
603
604 G_CONST_RETURN gchar*
605 g_getenv (const gchar *variable)
606 {
607 #ifndef G_OS_WIN32
608   g_return_val_if_fail (variable != NULL, NULL);
609
610   return getenv (variable);
611 #else
612   G_LOCK_DEFINE_STATIC (getenv);
613   struct env_struct
614   {
615     gchar *key;
616     gchar *value;
617   } *env;
618   static GArray *environs = NULL;
619   gchar *system_env;
620   guint length, i;
621   gchar dummy[2];
622
623   g_return_val_if_fail (variable != NULL, NULL);
624   
625   G_LOCK (getenv);
626
627   if (!environs)
628     environs = g_array_new (FALSE, FALSE, sizeof (struct env_struct));
629
630   /* First we try to find the envinronment variable inside the already
631    * found ones.
632    */
633
634   for (i = 0; i < environs->len; i++)
635     {
636       env = &g_array_index (environs, struct env_struct, i);
637       if (strcmp (env->key, variable) == 0)
638         {
639           g_assert (env->value);
640           G_UNLOCK (getenv);
641           return env->value;
642         }
643     }
644
645   /* If not found, we ask the system */
646
647   system_env = getenv (variable);
648   if (!system_env)
649     {
650       G_UNLOCK (getenv);
651       return NULL;
652     }
653
654   /* On Windows NT, it is relatively typical that environment variables
655    * contain references to other environment variables. Handle that by
656    * calling ExpandEnvironmentStrings.
657    */
658
659   g_array_set_size (environs, environs->len + 1);
660
661   env = &g_array_index (environs, struct env_struct, environs->len - 1);
662
663   /* First check how much space we need */
664   length = ExpandEnvironmentStrings (system_env, dummy, 2);
665
666   /* Then allocate that much, and actualy do the expansion and insert
667    * the new found pair into our buffer 
668    */
669
670   env->value = g_malloc (length);
671   env->key = g_strdup (variable);
672
673   ExpandEnvironmentStrings (system_env, env->value, length);
674
675   G_UNLOCK (getenv);
676   return env->value;
677 #endif
678 }
679
680
681 G_LOCK_DEFINE_STATIC (g_utils_global);
682
683 static  gchar   *g_tmp_dir = NULL;
684 static  gchar   *g_user_name = NULL;
685 static  gchar   *g_real_name = NULL;
686 static  gchar   *g_home_dir = NULL;
687
688 /* HOLDS: g_utils_global_lock */
689 static void
690 g_get_any_init (void)
691 {
692   if (!g_tmp_dir)
693     {
694       g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
695       if (!g_tmp_dir)
696         g_tmp_dir = g_strdup (g_getenv ("TMP"));
697       if (!g_tmp_dir)
698         g_tmp_dir = g_strdup (g_getenv ("TEMP"));
699       
700 #ifdef P_tmpdir
701       if (!g_tmp_dir)
702         {
703           int k;
704           g_tmp_dir = g_strdup (P_tmpdir);
705           k = strlen (g_tmp_dir);
706           if (g_tmp_dir[k-1] == G_DIR_SEPARATOR)
707             g_tmp_dir[k-1] = '\0';
708         }
709 #endif
710       
711       if (!g_tmp_dir)
712         {
713 #ifndef G_OS_WIN32
714           g_tmp_dir = g_strdup ("/tmp");
715 #else /* G_OS_WIN32 */
716           g_tmp_dir = g_strdup ("C:\\");
717 #endif /* G_OS_WIN32 */
718         }
719       
720       if (!g_home_dir)
721         g_home_dir = g_strdup (g_getenv ("HOME"));
722       
723 #ifdef G_OS_WIN32
724       /* In case HOME is Unix-style (it happens), convert it to
725        * Windows style.
726        */
727       if (g_home_dir)
728         {
729           gchar *p;
730           while ((p = strchr (g_home_dir, '/')) != NULL)
731             *p = '\\';
732         }
733
734       if (!g_home_dir)
735         {
736           /* USERPROFILE is probably the closest equivalent to $HOME? */
737           if (getenv ("USERPROFILE") != NULL)
738             g_home_dir = g_getenv ("USERPROFILE");
739         }
740
741       if (!g_home_dir)
742         {
743           /* At least at some time, HOMEDRIVE and HOMEPATH were used
744            * to point to the home directory, I think. But on Windows
745            * 2000 HOMEDRIVE seems to be equal to SYSTEMDRIVE, and
746            * HOMEPATH is its root "\"?
747            */
748           if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
749             {
750               gchar *homedrive, *homepath;
751               
752               homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
753               homepath = g_strdup (g_getenv ("HOMEPATH"));
754               
755               g_home_dir = g_strconcat (homedrive, homepath, NULL);
756               g_free (homedrive);
757               g_free (homepath);
758             }
759         }
760 #endif /* G_OS_WIN32 */
761       
762 #ifdef HAVE_PWD_H
763       {
764         struct passwd *pw = NULL;
765         gpointer buffer = NULL;
766         
767 #  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
768         struct passwd pwd;
769 #    ifdef _SC_GETPW_R_SIZE_MAX  
770         /* This reurns the maximum length */
771         guint bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
772 #    else /* _SC_GETPW_R_SIZE_MAX */
773         guint bufsize = 64;
774 #    endif /* _SC_GETPW_R_SIZE_MAX */
775         gint error;
776         
777         do
778           {
779             g_free (buffer);
780             buffer = g_malloc (bufsize);
781             errno = 0;
782             
783 #    ifdef HAVE_POSIX_GETPWUID_R
784             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
785             error = error < 0 ? errno : error;
786 #    else /* HAVE_NONPOSIX_GETPWUID_R */
787 #      ifdef _AIX
788             error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
789             pw = error == 0 ? &pwd : NULL;
790 #      else /* !_AIX */
791             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
792             error = pw ? 0 : errno;
793 #      endif /* !_AIX */            
794 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
795             
796             if (!pw)
797               {
798                 /* we bail out prematurely if the user id can't be found
799                  * (should be pretty rare case actually), or if the buffer
800                  * should be sufficiently big and lookups are still not
801                  * successfull.
802                  */
803                 if (error == 0 || error == ENOENT)
804                   {
805                     g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
806                                (gulong) getuid ());
807                     break;
808                   }
809                 if (bufsize > 32 * 1024)
810                   {
811                     g_warning ("getpwuid_r(): failed due to: %s.",
812                                g_strerror (error));
813                     break;
814                   }
815                 
816                 bufsize *= 2;
817               }
818           }
819         while (!pw);
820 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
821         
822         if (!pw)
823           {
824             setpwent ();
825             pw = getpwuid (getuid ());
826             endpwent ();
827           }
828         if (pw)
829           {
830             g_user_name = g_strdup (pw->pw_name);
831             g_real_name = g_strdup (pw->pw_gecos);
832             if (!g_home_dir)
833               g_home_dir = g_strdup (pw->pw_dir);
834           }
835         g_free (buffer);
836       }
837       
838 #else /* !HAVE_PWD_H */
839       
840 #  ifdef G_OS_WIN32
841       {
842         guint len = 17;
843         gchar buffer[17];
844         
845         if (GetUserName ((LPTSTR) buffer, (LPDWORD) &len))
846           {
847             g_user_name = g_strdup (buffer);
848             g_real_name = g_strdup (buffer);
849           }
850       }
851 #  endif /* G_OS_WIN32 */
852       
853 #endif /* !HAVE_PWD_H */
854       
855 #ifdef __EMX__
856       /* change '\\' in %HOME% to '/' */
857       g_strdelimit (g_home_dir, "\\",'/');
858 #endif
859       if (!g_user_name)
860         g_user_name = g_strdup ("somebody");
861       if (!g_real_name)
862         g_real_name = g_strdup ("Unknown");
863       else
864         {
865           gchar *p;
866
867           for (p = g_real_name; *p; p++)
868             if (*p == ',')
869               {
870                 *p = 0;
871                 p = g_strdup (g_real_name);
872                 g_free (g_real_name);
873                 g_real_name = p;
874                 break;
875               }
876         }
877     }
878 }
879
880 G_CONST_RETURN gchar*
881 g_get_user_name (void)
882 {
883   G_LOCK (g_utils_global);
884   if (!g_tmp_dir)
885     g_get_any_init ();
886   G_UNLOCK (g_utils_global);
887   
888   return g_user_name;
889 }
890
891 G_CONST_RETURN gchar*
892 g_get_real_name (void)
893 {
894   G_LOCK (g_utils_global);
895   if (!g_tmp_dir)
896     g_get_any_init ();
897   G_UNLOCK (g_utils_global);
898  
899   return g_real_name;
900 }
901
902 /* Return the home directory of the user. If there is a HOME
903  * environment variable, its value is returned, otherwise use some
904  * system-dependent way of finding it out. If no home directory can be
905  * deduced, return NULL.
906  */
907
908 G_CONST_RETURN gchar*
909 g_get_home_dir (void)
910 {
911   G_LOCK (g_utils_global);
912   if (!g_tmp_dir)
913     g_get_any_init ();
914   G_UNLOCK (g_utils_global);
915   
916   return g_home_dir;
917 }
918
919 /* Return a directory to be used to store temporary files. This is the
920  * value of the TMPDIR, TMP or TEMP environment variables (they are
921  * checked in that order). If none of those exist, use P_tmpdir from
922  * stdio.h.  If that isn't defined, return "/tmp" on POSIXly systems,
923  * and C:\ on Windows.
924  */
925
926 G_CONST_RETURN gchar*
927 g_get_tmp_dir (void)
928 {
929   G_LOCK (g_utils_global);
930   if (!g_tmp_dir)
931     g_get_any_init ();
932   G_UNLOCK (g_utils_global);
933   
934   return g_tmp_dir;
935 }
936
937 static gchar *g_prgname = NULL;
938
939 gchar*
940 g_get_prgname (void)
941 {
942   gchar* retval;
943
944   G_LOCK (g_utils_global);
945   retval = g_prgname;
946   G_UNLOCK (g_utils_global);
947
948   return retval;
949 }
950
951 void
952 g_set_prgname (const gchar *prgname)
953 {
954   gchar *c;
955     
956   G_LOCK (g_utils_global);
957   c = g_prgname;
958   g_prgname = g_strdup (prgname);
959   g_free (c);
960   G_UNLOCK (g_utils_global);
961 }
962
963 guint
964 g_direct_hash (gconstpointer v)
965 {
966   return GPOINTER_TO_UINT (v);
967 }
968
969 gboolean
970 g_direct_equal (gconstpointer v1,
971                 gconstpointer v2)
972 {
973   return v1 == v2;
974 }
975
976 gboolean
977 g_int_equal (gconstpointer v1,
978              gconstpointer v2)
979 {
980   return *((const gint*) v1) == *((const gint*) v2);
981 }
982
983 guint
984 g_int_hash (gconstpointer v)
985 {
986   return *(const gint*) v;
987 }
988
989 /**
990  * g_get_codeset:
991  * 
992  * Get the codeset for the current locale.
993  * 
994  * Return value: a newly allocated string containing the name
995  * of the codeset. This string must be freed with g_free().
996  **/
997 gchar *
998 g_get_codeset (void)
999 {
1000 #ifdef HAVE_CODESET  
1001   char *result = nl_langinfo (CODESET);
1002   return g_strdup (result);
1003 #else
1004 #ifndef G_OS_WIN32
1005   /* FIXME: Do something more intelligent based on setlocale (LC_CTYPE, NULL)
1006    */
1007   return g_strdup ("ISO-8859-1");
1008 #else
1009   return g_strdup_printf ("CP%d", GetACP ());
1010 #endif
1011 #endif
1012 }
1013
1014 #ifdef ENABLE_NLS
1015
1016 #include <libintl.h>
1017
1018
1019 #ifdef G_OS_WIN32
1020
1021 #define GLIB_LOCALE_DIR                                         \
1022   g_win32_get_package_installation_subdirectory                 \
1023   (GETTEXT_PACKAGE, g_strdup_printf ("glib-%d.%d.dll",          \
1024                                      GLIB_MAJOR_VERSION,        \
1025                                      GLIB_MINOR_VERSION),       \
1026    "locale")
1027
1028 #endif /* G_OS_WIN32 */
1029
1030 G_CONST_RETURN gchar *
1031 _glib_gettext (const gchar *str)
1032 {
1033   gboolean _glib_gettext_initialized = FALSE;
1034
1035   if (!_glib_gettext_initialized)
1036     {
1037       bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
1038       _glib_gettext_initialized = TRUE;
1039     }
1040   
1041   return dgettext (GETTEXT_PACKAGE, str);
1042 }
1043
1044 #endif /* ENABLE_NLS */
1045
1046