Look also for (illegal) forward slashes in the template.
[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 #  include <io.h>
73 #endif /* G_OS_WIN32 */
74
75 #ifdef HAVE_CODESET
76 #include <langinfo.h>
77 #endif
78
79 const guint glib_major_version = GLIB_MAJOR_VERSION;
80 const guint glib_minor_version = GLIB_MINOR_VERSION;
81 const guint glib_micro_version = GLIB_MICRO_VERSION;
82 const guint glib_interface_age = GLIB_INTERFACE_AGE;
83 const guint glib_binary_age = GLIB_BINARY_AGE;
84
85 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
86 void 
87 g_memmove (gpointer dest, gconstpointer src, gulong len)
88 {
89   gchar* destptr = dest;
90   const gchar* srcptr = src;
91   if (src + len < dest || dest + len < src)
92     {
93       bcopy (src, dest, len);
94       return;
95     }
96   else if (dest <= src)
97     {
98       while (len--)
99         *(destptr++) = *(srcptr++);
100     }
101   else
102     {
103       destptr += len;
104       srcptr += len;
105       while (len--)
106         *(--destptr) = *(--srcptr);
107     }
108 }
109 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
110
111 void
112 g_atexit (GVoidFunc func)
113 {
114   gint result;
115   gchar *error = NULL;
116
117   /* keep this in sync with glib.h */
118
119 #ifdef  G_NATIVE_ATEXIT
120   result = ATEXIT (func);
121   if (result)
122     error = g_strerror (errno);
123 #elif defined (HAVE_ATEXIT)
124 #  ifdef NeXT /* @#%@! NeXTStep */
125   result = !atexit ((void (*)(void)) func);
126   if (result)
127     error = g_strerror (errno);
128 #  else
129   result = atexit ((void (*)(void)) func);
130   if (result)
131     error = g_strerror (errno);
132 #  endif /* NeXT */
133 #elif defined (HAVE_ON_EXIT)
134   result = on_exit ((void (*)(int, void *)) func, NULL);
135   if (result)
136     error = g_strerror (errno);
137 #else
138   result = 0;
139   error = "no implementation";
140 #endif /* G_NATIVE_ATEXIT */
141
142   if (error)
143     g_error ("Could not register atexit() function: %s", error);
144 }
145
146 /* Based on execvp() from GNU Libc.
147  * Some of this code is cut-and-pasted into gspawn.c
148  */
149
150 static gchar*
151 my_strchrnul (const gchar *str, gchar c)
152 {
153   gchar *p = (gchar*)str;
154   while (*p && (*p != c))
155     ++p;
156
157   return p;
158 }
159
160 /**
161  * g_find_program_in_path:
162  * @program: a program name
163  * 
164  * Locates the first executable named @program in the user's path, in the
165  * same way that execvp() would locate it. Returns an allocated string
166  * with the absolute path name, or NULL if the program is not found in
167  * the path. If @program is already an absolute path, returns a copy of
168  * @program if @program exists and is executable, and NULL otherwise.
169  * 
170  * Return value: absolute path, or NULL
171  **/
172 gchar*
173 g_find_program_in_path (const gchar *program)
174 {
175   gchar *path, *p, *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 gchar*
378 g_basename (const gchar    *file_name)
379 {
380   register gchar *base;
381 #ifdef G_ENABLE_DEBUG
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 #endif
465
466   return FALSE;
467 }
468
469 gchar*
470 g_path_skip_root (gchar *file_name)
471 {
472   g_return_val_if_fail (file_name != NULL, NULL);
473   
474 #ifdef G_OS_WIN32
475   /* Skip \\server\share\ */
476   if (file_name[0] == G_DIR_SEPARATOR &&
477       file_name[1] == G_DIR_SEPARATOR &&
478       file_name[2] && 
479       strchr (file_name + 2, G_DIR_SEPARATOR) > file_name + 2)
480     return strchr (file_name + 2, G_DIR_SEPARATOR) + 1;
481 #endif
482   
483   /* Skip initial slashes */
484   if (file_name[0] == G_DIR_SEPARATOR)
485     {
486       while (file_name[0] == G_DIR_SEPARATOR)
487         file_name++;
488       return file_name;
489     }
490
491 #ifdef G_OS_WIN32
492   /* Skip X:\ */
493   if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
494     return file_name + 3;
495 #endif
496
497   return NULL;
498 }
499
500 gchar*
501 g_path_get_dirname (const gchar    *file_name)
502 {
503   register gchar *base;
504   register guint len;
505   
506   g_return_val_if_fail (file_name != NULL, NULL);
507   
508   base = strrchr (file_name, G_DIR_SEPARATOR);
509   if (!base)
510     return g_strdup (".");
511   while (base > file_name && *base == G_DIR_SEPARATOR)
512     base--;
513   len = (guint) 1 + base - file_name;
514   
515   base = g_new (gchar, len + 1);
516   g_memmove (base, file_name, len);
517   base[len] = 0;
518   
519   return base;
520 }
521
522 gchar*
523 g_dirname (const gchar     *file_name)
524 {
525 #ifdef G_ENABLE_DEBUG
526   static gboolean first_call = TRUE;
527
528   if (first_call)
529     {
530       g_message ("g_dirname() is deprecated. Use g_path_get_dirname() instead.");
531       first_call = FALSE;
532     }
533 #endif /* G_ENABLE_DEBUG */
534
535   return g_path_get_dirname (file_name);
536 }
537
538 gchar*
539 g_get_current_dir (void)
540 {
541   gchar *buffer = NULL;
542   gchar *dir = NULL;
543   static gulong max_len = 0;
544
545   if (max_len == 0) 
546     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
547   
548   /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
549    * and, if that wasn't bad enough, hangs in doing so.
550    */
551 #if     (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
552   buffer = g_new (gchar, max_len + 1);
553   *buffer = 0;
554   dir = getwd (buffer);
555 #else   /* !sun || !HAVE_GETCWD */
556   while (max_len < G_MAXULONG / 2)
557     {
558       buffer = g_new (gchar, max_len + 1);
559       *buffer = 0;
560       dir = getcwd (buffer, max_len);
561
562       if (dir || errno != ERANGE)
563         break;
564
565       g_free (buffer);
566       max_len *= 2;
567     }
568 #endif  /* !sun || !HAVE_GETCWD */
569   
570   if (!dir || !*buffer)
571     {
572       /* hm, should we g_error() out here?
573        * this can happen if e.g. "./" has mode \0000
574        */
575       buffer[0] = G_DIR_SEPARATOR;
576       buffer[1] = 0;
577     }
578
579   dir = g_strdup (buffer);
580   g_free (buffer);
581   
582   return dir;
583 }
584
585 gchar*
586 g_getenv (const gchar *variable)
587 {
588 #ifndef G_OS_WIN32
589   g_return_val_if_fail (variable != NULL, NULL);
590
591   return getenv (variable);
592 #else
593   G_LOCK_DEFINE_STATIC (getenv);
594   struct env_struct
595   {
596     gchar *key;
597     gchar *value;
598   } *env;
599   static GArray *environs = NULL;
600   gchar *system_env;
601   guint length, i;
602   gchar dummy[2];
603
604   g_return_val_if_fail (variable != NULL, NULL);
605   
606   G_LOCK (getenv);
607
608   if (!environs)
609     environs = g_array_new (FALSE, FALSE, sizeof (struct env_struct));
610
611   /* First we try to find the envinronment variable inside the already
612    * found ones.
613    */
614
615   for (i = 0; i < environs->len; i++)
616     {
617       env = &g_array_index (environs, struct env_struct, i);
618       if (strcmp (env->key, variable) == 0)
619         {
620           g_assert (env->value);
621           G_UNLOCK (getenv);
622           return env->value;
623         }
624     }
625
626   /* If not found, we ask the system */
627
628   system_env = getenv (variable);
629   if (!system_env)
630     {
631       G_UNLOCK (getenv);
632       return NULL;
633     }
634
635   /* On Windows NT, it is relatively typical that environment variables
636    * contain references to other environment variables. Handle that by
637    * calling ExpandEnvironmentStrings.
638    */
639
640   g_array_set_size (environs, environs->len + 1);
641
642   env = &g_array_index (environs, struct env_struct, environs->len - 1);
643
644   /* First check how much space we need */
645   length = ExpandEnvironmentStrings (system_env, dummy, 2);
646
647   /* Then allocate that much, and actualy do the expansion and insert
648    * the new found pair into our buffer 
649    */
650
651   env->value = g_malloc (length);
652   env->key = g_strdup (variable);
653
654   ExpandEnvironmentStrings (system_env, env->value, length);
655
656   G_UNLOCK (getenv);
657   return env->value;
658 #endif
659 }
660
661
662 G_LOCK_DEFINE_STATIC (g_utils_global);
663
664 static  gchar   *g_tmp_dir = NULL;
665 static  gchar   *g_user_name = NULL;
666 static  gchar   *g_real_name = NULL;
667 static  gchar   *g_home_dir = NULL;
668
669 /* HOLDS: g_utils_global_lock */
670 static void
671 g_get_any_init (void)
672 {
673   if (!g_tmp_dir)
674     {
675       g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
676       if (!g_tmp_dir)
677         g_tmp_dir = g_strdup (g_getenv ("TMP"));
678       if (!g_tmp_dir)
679         g_tmp_dir = g_strdup (g_getenv ("TEMP"));
680       
681 #ifdef P_tmpdir
682       if (!g_tmp_dir)
683         {
684           int k;
685           g_tmp_dir = g_strdup (P_tmpdir);
686           k = strlen (g_tmp_dir);
687           if (g_tmp_dir[k-1] == G_DIR_SEPARATOR)
688             g_tmp_dir[k-1] = '\0';
689         }
690 #endif
691       
692       if (!g_tmp_dir)
693         {
694 #ifndef G_OS_WIN32
695           g_tmp_dir = g_strdup ("/tmp");
696 #else /* G_OS_WIN32 */
697           g_tmp_dir = g_strdup ("C:\\");
698 #endif /* G_OS_WIN32 */
699         }
700       
701       if (!g_home_dir)
702         g_home_dir = g_strdup (g_getenv ("HOME"));
703       
704 #ifdef G_OS_WIN32
705       /* In case HOME is Unix-style (it happens), convert it to
706        * Windows style.
707        */
708       if (g_home_dir)
709         {
710           gchar *p;
711           while ((p = strchr (g_home_dir, '/')) != NULL)
712             *p = '\\';
713         }
714       else
715         {
716           /* The official way to specify a home directory on NT is
717            * the HOMEDRIVE and HOMEPATH environment variables. At least
718            * it was at some time.
719            */
720           if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
721             {
722               gchar *homedrive, *homepath;
723               
724               homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
725               homepath = g_strdup (g_getenv ("HOMEPATH"));
726               
727               g_home_dir = g_strconcat (homedrive, homepath, NULL);
728               g_free (homedrive);
729               g_free (homepath);
730             }
731         }
732 #endif /* G_OS_WIN32 */
733       
734 #ifdef HAVE_PWD_H
735       {
736         struct passwd *pw = NULL;
737         gpointer buffer = NULL;
738         
739 #  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
740         struct passwd pwd;
741 #    ifdef _SC_GETPW_R_SIZE_MAX  
742         /* This reurns the maximum length */
743         guint bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
744 #    else /* _SC_GETPW_R_SIZE_MAX */
745         guint bufsize = 64;
746 #    endif /* _SC_GETPW_R_SIZE_MAX */
747         gint error;
748         
749         do
750           {
751             g_free (buffer);
752             buffer = g_malloc (bufsize);
753             errno = 0;
754             
755 #    ifdef HAVE_POSIX_GETPWUID_R
756             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
757             error = error < 0 ? errno : error;
758 #    else /* HAVE_NONPOSIX_GETPWUID_R */
759 #      ifdef _AIX
760             error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
761             pw = error == 0 ? &pwd : NULL;
762 #      else /* !_AIX */
763             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
764             error = pw ? 0 : errno;
765 #      endif /* !_AIX */            
766 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
767             
768             if (!pw)
769               {
770                 /* we bail out prematurely if the user id can't be found
771                  * (should be pretty rare case actually), or if the buffer
772                  * should be sufficiently big and lookups are still not
773                  * successfull.
774                  */
775                 if (error == 0 || error == ENOENT)
776                   {
777                     g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
778                                (gulong) getuid ());
779                     break;
780                   }
781                 if (bufsize > 32 * 1024)
782                   {
783                     g_warning ("getpwuid_r(): failed due to: %s.",
784                                g_strerror (error));
785                     break;
786                   }
787                 
788                 bufsize *= 2;
789               }
790           }
791         while (!pw);
792 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
793         
794         if (!pw)
795           {
796             setpwent ();
797             pw = getpwuid (getuid ());
798             endpwent ();
799           }
800         if (pw)
801           {
802             g_user_name = g_strdup (pw->pw_name);
803             g_real_name = g_strdup (pw->pw_gecos);
804             if (!g_home_dir)
805               g_home_dir = g_strdup (pw->pw_dir);
806           }
807         g_free (buffer);
808       }
809       
810 #else /* !HAVE_PWD_H */
811       
812 #  ifdef G_OS_WIN32
813       {
814         guint len = 17;
815         gchar buffer[17];
816         
817         if (GetUserName ((LPTSTR) buffer, (LPDWORD) &len))
818           {
819             g_user_name = g_strdup (buffer);
820             g_real_name = g_strdup (buffer);
821           }
822       }
823 #  endif /* G_OS_WIN32 */
824       
825 #endif /* !HAVE_PWD_H */
826       
827 #ifdef __EMX__
828       /* change '\\' in %HOME% to '/' */
829       g_strdelimit (g_home_dir, "\\",'/');
830 #endif
831       if (!g_user_name)
832         g_user_name = g_strdup ("somebody");
833       if (!g_real_name)
834         g_real_name = g_strdup ("Unknown");
835       else
836         {
837           gchar *p;
838
839           for (p = g_real_name; *p; p++)
840             if (*p == ',')
841               {
842                 *p = 0;
843                 p = g_strdup (g_real_name);
844                 g_free (g_real_name);
845                 g_real_name = p;
846                 break;
847               }
848         }
849     }
850 }
851
852 gchar*
853 g_get_user_name (void)
854 {
855   G_LOCK (g_utils_global);
856   if (!g_tmp_dir)
857     g_get_any_init ();
858   G_UNLOCK (g_utils_global);
859   
860   return g_user_name;
861 }
862
863 gchar*
864 g_get_real_name (void)
865 {
866   G_LOCK (g_utils_global);
867   if (!g_tmp_dir)
868     g_get_any_init ();
869   G_UNLOCK (g_utils_global);
870  
871   return g_real_name;
872 }
873
874 /* Return the home directory of the user. If there is a HOME
875  * environment variable, its value is returned, otherwise use some
876  * system-dependent way of finding it out. If no home directory can be
877  * deduced, return NULL.
878  */
879
880 gchar*
881 g_get_home_dir (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_home_dir;
889 }
890
891 /* Return a directory to be used to store temporary files. This is the
892  * value of the TMPDIR, TMP or TEMP environment variables (they are
893  * checked in that order). If none of those exist, use P_tmpdir from
894  * stdio.h.  If that isn't defined, return "/tmp" on POSIXly systems,
895  * and C:\ on Windows.
896  */
897
898 gchar*
899 g_get_tmp_dir (void)
900 {
901   G_LOCK (g_utils_global);
902   if (!g_tmp_dir)
903     g_get_any_init ();
904   G_UNLOCK (g_utils_global);
905   
906   return g_tmp_dir;
907 }
908
909 static gchar *g_prgname = NULL;
910
911 gchar*
912 g_get_prgname (void)
913 {
914   gchar* retval;
915
916   G_LOCK (g_utils_global);
917   retval = g_prgname;
918   G_UNLOCK (g_utils_global);
919
920   return retval;
921 }
922
923 void
924 g_set_prgname (const gchar *prgname)
925 {
926   gchar *c;
927     
928   G_LOCK (g_utils_global);
929   c = g_prgname;
930   g_prgname = g_strdup (prgname);
931   g_free (c);
932   G_UNLOCK (g_utils_global);
933 }
934
935 guint
936 g_direct_hash (gconstpointer v)
937 {
938   return GPOINTER_TO_UINT (v);
939 }
940
941 gboolean
942 g_direct_equal (gconstpointer v1,
943                 gconstpointer v2)
944 {
945   return v1 == v2;
946 }
947
948 gboolean
949 g_int_equal (gconstpointer v1,
950              gconstpointer v2)
951 {
952   return *((const gint*) v1) == *((const gint*) v2);
953 }
954
955 guint
956 g_int_hash (gconstpointer v)
957 {
958   return *(const gint*) v;
959 }
960
961 /**
962  * g_get_codeset:
963  * 
964  * Get the codeset for the current locale.
965  * 
966  * Return value: a newly allocated string containing the name
967  * of the codeset. This string must be freed with g_free().
968  **/
969 gchar *
970 g_get_codeset (void)
971 {
972 #ifdef HAVE_CODESET  
973   char *result = nl_langinfo (CODESET);
974   return g_strdup (result);
975 #else
976 #ifndef G_OS_WIN32
977   /* FIXME: Do something more intelligent based on setlocale (LC_CTYPE, NULL)
978    */
979   return g_strdup ("ISO-8859-1");
980 #else
981   /* On Win32 we always use UTF-8. At least in GDK. SO should we
982    * therefore return that?
983    */
984   return g_strdup ("UTF-8");
985 #endif
986 #endif
987 }