Use getpwuid_r with the right signature, if available.
[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 Library 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  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library 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  * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include "glibconfig.h"
29
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
33 #include <stdarg.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <errno.h>
38 #ifdef HAVE_PWD_H
39 #include <pwd.h>
40 #endif
41 #include <sys/types.h>
42 #ifdef HAVE_SYS_PARAM_H
43 #include <sys/param.h>
44 #endif
45
46 #ifdef NATIVE_WIN32
47 #  define STRICT                        /* Strict typing, please */
48 #  include <windows.h>
49 #  include <direct.h>
50 #  include <errno.h>
51 #  include <ctype.h>
52 #  ifdef _MSC_VER
53 #    include <io.h>
54 #  endif /* _MSC_VER */
55 #endif /* NATIVE_WIN32 */
56
57 /* implement Glib's inline functions
58  */
59 #define G_INLINE_FUNC extern
60 #define G_CAN_INLINE 1
61 #include "glib.h"
62
63 #ifdef  MAXPATHLEN
64 #define G_PATH_LENGTH   (MAXPATHLEN + 1)
65 #elif   defined (PATH_MAX)
66 #define G_PATH_LENGTH   (PATH_MAX + 1)
67 #else   /* !MAXPATHLEN */
68 #define G_PATH_LENGTH   (2048 + 1)
69 #endif  /* !MAXPATHLEN && !PATH_MAX */
70
71 const guint glib_major_version = GLIB_MAJOR_VERSION;
72 const guint glib_minor_version = GLIB_MINOR_VERSION;
73 const guint glib_micro_version = GLIB_MICRO_VERSION;
74 const guint glib_interface_age = GLIB_INTERFACE_AGE;
75 const guint glib_binary_age = GLIB_BINARY_AGE;
76
77 #if defined (NATIVE_WIN32) && defined (__LCC__)
78 int __stdcall 
79 LibMain (void         *hinstDll,
80          unsigned long dwReason,
81          void         *reserved)
82 {
83   return 1;
84 }
85 #endif /* NATIVE_WIN32 && __LCC__ */
86
87 void
88 g_atexit (GVoidFunc func)
89 {
90   gint result;
91   gchar *error = NULL;
92
93   /* keep this in sync with glib.h */
94
95 #ifdef  G_NATIVE_ATEXIT
96   result = ATEXIT (func);
97   if (result)
98     error = g_strerror (errno);
99 #elif defined (HAVE_ATEXIT)
100 #  ifdef NeXT /* @#%@! NeXTStep */
101   result = !atexit ((void (*)(void)) func);
102   if (result)
103     error = g_strerror (errno);
104 #  else
105   result = atexit ((void (*)(void)) func);
106   if (result)
107     error = g_strerror (errno);
108 #  endif /* NeXT */
109 #elif defined (HAVE_ON_EXIT)
110   result = on_exit ((void (*)(int, void *)) func, NULL);
111   if (result)
112     error = g_strerror (errno);
113 #else
114   result = 0;
115   error = "no implementation";
116 #endif /* G_NATIVE_ATEXIT */
117
118   if (error)
119     g_error ("Could not register atexit() function: %s", error);
120 }
121
122 gint
123 g_snprintf (gchar       *str,
124             gulong       n,
125             gchar const *fmt,
126             ...)
127 {
128 #ifdef  HAVE_VSNPRINTF
129   va_list args;
130   gint retval;
131   
132   va_start (args, fmt);
133   retval = vsnprintf (str, n, fmt, args);
134   va_end (args);
135   
136   return retval;
137 #else   /* !HAVE_VSNPRINTF */
138   gchar *printed;
139   va_list args;
140   
141   va_start (args, fmt);
142   printed = g_strdup_vprintf (fmt, args);
143   va_end (args);
144   
145   strncpy (str, printed, n);
146   str[n-1] = '\0';
147
148   g_free (printed);
149   
150   return strlen (str);
151 #endif  /* !HAVE_VSNPRINTF */
152 }
153
154 gint
155 g_vsnprintf (gchar       *str,
156              gulong       n,
157              gchar const *fmt,
158              va_list      args)
159 {
160 #ifdef  HAVE_VSNPRINTF
161   gint retval;
162   
163   retval = vsnprintf (str, n, fmt, args);
164   
165   return retval;
166 #else   /* !HAVE_VSNPRINTF */
167   gchar *printed;
168   
169   printed = g_strdup_vprintf (fmt, args);
170   strncpy (str, printed, n);
171   str[n-1] = '\0';
172
173   g_free (printed);
174   
175   return strlen (str);
176 #endif /* !HAVE_VSNPRINTF */
177 }
178
179 guint        
180 g_parse_debug_string  (const gchar *string, 
181                        GDebugKey   *keys, 
182                        guint        nkeys)
183 {
184   guint i;
185   guint result = 0;
186   
187   g_return_val_if_fail (string != NULL, 0);
188   
189   if (!g_strcasecmp (string, "all"))
190     {
191       for (i=0; i<nkeys; i++)
192         result |= keys[i].value;
193     }
194   else
195     {
196       gchar *str = g_strdup (string);
197       gchar *p = str;
198       gchar *q;
199       gboolean done = FALSE;
200       
201       while (*p && !done)
202         {
203           q = strchr (p, ':');
204           if (!q)
205             {
206               q = p + strlen(p);
207               done = TRUE;
208             }
209           
210           *q = 0;
211           
212           for (i=0; i<nkeys; i++)
213             if (!g_strcasecmp(keys[i].key, p))
214               result |= keys[i].value;
215           
216           p = q+1;
217         }
218       
219       g_free (str);
220     }
221   
222   return result;
223 }
224
225 gchar*
226 g_basename (const gchar    *file_name)
227 {
228   register gchar *base;
229   
230   g_return_val_if_fail (file_name != NULL, NULL);
231   
232   base = strrchr (file_name, G_DIR_SEPARATOR);
233   if (base)
234     return base + 1;
235
236 #ifdef NATIVE_WIN32
237   if (isalpha (file_name[0]) && file_name[1] == ':')
238     return (gchar*) file_name + 2;
239 #endif /* NATIVE_WIN32 */
240   
241   return (gchar*) file_name;
242 }
243
244 gboolean
245 g_path_is_absolute (const gchar *file_name)
246 {
247   g_return_val_if_fail (file_name != NULL, FALSE);
248   
249   if (file_name[0] == G_DIR_SEPARATOR)
250     return TRUE;
251
252 #ifdef NATIVE_WIN32
253   if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
254     return TRUE;
255 #endif
256
257   return FALSE;
258 }
259
260 gchar*
261 g_path_skip_root (gchar *file_name)
262 {
263   g_return_val_if_fail (file_name != NULL, NULL);
264   
265   if (file_name[0] == G_DIR_SEPARATOR)
266     return file_name + 1;
267
268 #ifdef NATIVE_WIN32
269   if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
270     return file_name + 3;
271 #endif
272
273   return NULL;
274 }
275
276 gchar*
277 g_dirname (const gchar     *file_name)
278 {
279   register gchar *base;
280   register guint len;
281   
282   g_return_val_if_fail (file_name != NULL, NULL);
283   
284   base = strrchr (file_name, G_DIR_SEPARATOR);
285   if (!base)
286     return g_strdup (".");
287   while (base > file_name && *base == G_DIR_SEPARATOR)
288     base--;
289   len = (guint) 1 + base - file_name;
290   
291   base = g_new (gchar, len + 1);
292   g_memmove (base, file_name, len);
293   base[len] = 0;
294   
295   return base;
296 }
297
298 gchar*
299 g_get_current_dir (void)
300 {
301   gchar *buffer;
302   gchar *dir;
303
304   buffer = g_new (gchar, G_PATH_LENGTH);
305   *buffer = 0;
306   
307   /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
308    * and, if that wasn't bad enough, hangs in doing so.
309    */
310 #if     defined (sun) && !defined (__SVR4)
311   dir = getwd (buffer);
312 #else   /* !sun */
313   dir = getcwd (buffer, G_PATH_LENGTH - 1);
314 #endif  /* !sun */
315   
316   if (!dir || !*buffer)
317     {
318       /* hm, should we g_error() out here?
319        * this can happen if e.g. "./" has mode \0000
320        */
321       buffer[0] = G_DIR_SEPARATOR;
322       buffer[1] = 0;
323     }
324
325   dir = g_strdup (buffer);
326   g_free (buffer);
327   
328   return dir;
329 }
330
331 gchar*
332 g_getenv (const gchar *variable)
333 {
334 #ifndef NATIVE_WIN32
335   g_return_val_if_fail (variable != NULL, NULL);
336
337   return getenv (variable);
338 #else
339   gchar *v;
340   guint k;
341   static gchar *p = NULL;
342   static gint l;
343   gchar dummy[2];
344
345   g_return_val_if_fail (variable != NULL, NULL);
346   
347   v = getenv (variable);
348   if (!v)
349     return NULL;
350   
351   /* On Windows NT, it is relatively typical that environment variables
352    * contain references to other environment variables. Handle that by
353    * calling ExpandEnvironmentStrings.
354    */
355
356   /* First check how much space we need */
357   k = ExpandEnvironmentStrings (v, dummy, 2);
358   /* Then allocate that much, and actualy do the expansion */
359   if (p == NULL)
360     {
361       p = g_malloc (k);
362       l = k;
363     }
364   else if (k > l)
365     {
366       p = g_realloc (p, k);
367       l = k;
368     }
369   ExpandEnvironmentStrings (v, p, k);
370   return p;
371 #endif
372 }
373
374 G_LOCK_DECLARE_STATIC (g_utils_global);
375
376 static  gchar   *g_tmp_dir = NULL;
377 static  gchar   *g_user_name = NULL;
378 static  gchar   *g_real_name = NULL;
379 static  gchar   *g_home_dir = NULL;
380
381 /* HOLDS: g_utils_global_lock */
382 static void
383 g_get_any_init (void)
384 {
385   if (!g_tmp_dir)
386     {
387       g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
388       if (!g_tmp_dir)
389         g_tmp_dir = g_strdup (g_getenv ("TMP"));
390       if (!g_tmp_dir)
391         g_tmp_dir = g_strdup (g_getenv ("TEMP"));
392       
393 #ifdef P_tmpdir
394       if (!g_tmp_dir)
395         {
396           int k;
397           g_tmp_dir = g_strdup (P_tmpdir);
398           k = strlen (g_tmp_dir);
399           if (g_tmp_dir[k-1] == G_DIR_SEPARATOR)
400             g_tmp_dir[k-1] = '\0';
401         }
402 #endif
403       if (!g_tmp_dir)
404         {
405 #ifndef NATIVE_WIN32
406           g_tmp_dir = g_strdup ("/tmp");
407 #else /* NATIVE_WIN32 */
408           g_tmp_dir = g_strdup ("C:\\");
409 #endif /* NATIVE_WIN32 */
410         }
411       
412 #ifdef NATIVE_WIN32
413       /* The official way to specify a home directory on NT is
414        * the HOMEDRIVE and HOMEPATH environment variables.
415        *
416        * This is inside #ifdef NATIVE_WIN32 because with the cygwin dll,
417        * HOME should be a POSIX style pathname.
418        */
419       
420       if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
421         {
422           gchar *homedrive, *homepath;
423
424           homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
425           homepath = g_strdup (g_getenv ("HOMEPATH"));
426
427           g_home_dir = g_strconcat (homedrive, homepath, NULL);
428           g_free (homedrive);
429           g_free (homepath);
430         }
431       if (!g_home_dir)
432         g_home_dir = g_strdup (g_getenv ("HOME"));
433 #else
434       g_home_dir = g_strdup (g_getenv ("HOME"));
435 #endif
436       
437 #ifdef HAVE_PWD_H
438       {
439         struct passwd *pw = NULL, pwd;
440         gpointer buffer = NULL;
441         guint bufsize = sizeof (struct passwd);
442 #  ifdef HAVE_GETPWUID_R 
443         while (TRUE)
444           {
445             int error = 0;
446             buffer = g_realloc (buffer, bufsize);
447 #    ifdef HAVE_GETPWUID_R_POSIX
448             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
449             if (error == 0)
450               break;
451 #    else /* HAVE_GETPWUID_R_POSIX */
452             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
453             if (pw)
454               break;
455             error = errno;
456 #    endif /* HAVE_GETPWUID_R_POSIX */
457             if (error != ERANGE)
458               g_error( "Could not read account information: %s", 
459                        g_strerror (error));
460             bufsize *= 2;
461           }
462 #  else /* HAVE_GETPWUID_R */
463 #    if defined(G_THREADS_ENABLED) && defined(__GNUC__)
464 #    warning "the `g_get_(user_name|real_name|home_dir|tmp_dir)'"
465 #    warning "functions will not be MT-safe at their first call"
466 #    warning "because there is no `getpwuid_r' on your system."
467 #    endif
468         setpwent ();
469         pw = getpwuid (getuid ());
470         endpwent ();
471 #  endif /* HAVE_GETPWUID_R */
472         
473         if (pw)
474           {
475             g_user_name = g_strdup (pw->pw_name);
476             g_real_name = g_strdup (pw->pw_gecos);
477             if (!g_home_dir)
478               g_home_dir = g_strdup (pw->pw_dir);
479           }
480         g_free (buffer);
481       }
482 #else /* !HAVE_PWD_H */
483 #  ifdef NATIVE_WIN32
484       {
485         guint len = 17;
486         
487         g_user_name = g_new (gchar, len);
488         
489         if (!GetUserName (g_user_name, &len))
490           {
491             g_free (g_user_name);
492             g_user_name = g_strdup ("somebody");
493             g_real_name = g_strdup ("Unknown");
494           }
495         else
496           g_real_name = g_strdup (g_user_name);
497       }
498 #  else /* !NATIVE_WIN32 */
499       g_user_name = g_strdup ("somebody");
500       g_real_name = g_strdup ("Unknown");
501       g_home_dir = NULL;
502 #  endif /* !NATIVE_WIN32 */
503 #endif /* !HAVE_PWD_H */
504     }  
505 }
506
507 gchar*
508 g_get_user_name (void)
509 {
510   G_LOCK (g_utils_global);
511   if (!g_tmp_dir)
512     g_get_any_init ();
513   G_UNLOCK (g_utils_global);
514   
515   return g_user_name;
516 }
517
518 gchar*
519 g_get_real_name (void)
520 {
521   G_LOCK (g_utils_global);
522   if (!g_tmp_dir)
523     g_get_any_init ();
524   G_UNLOCK (g_utils_global);
525  
526   return g_real_name;
527 }
528
529 /* Return the home directory of the user. If there is a HOME
530  * environment variable, its value is returned, otherwise use some
531  * system-dependent way of finding it out. If no home directory can be
532  * deduced, return NULL.
533  */
534
535 gchar*
536 g_get_home_dir (void)
537 {
538   G_LOCK (g_utils_global);
539   if (!g_tmp_dir)
540     g_get_any_init ();
541   G_UNLOCK (g_utils_global);
542   
543   return g_home_dir;
544 }
545
546 /* Return a directory to be used to store temporary files. This is the
547  * value of the TMPDIR, TMP or TEMP environment variables (they are
548  * checked in that order). If none of those exist, use P_tmpdir from
549  * stdio.h.  If that isn't defined, return "/tmp" on POSIXly systems,
550  * and C:\ on Windows.
551  */
552
553 gchar*
554 g_get_tmp_dir (void)
555 {
556   G_LOCK (g_utils_global);
557   if (!g_tmp_dir)
558     g_get_any_init ();
559   G_UNLOCK (g_utils_global);
560   
561   return g_tmp_dir;
562 }
563
564 static gchar *g_prgname = NULL;
565
566 gchar*
567 g_get_prgname (void)
568 {
569   gchar* retval;
570
571   G_LOCK (g_utils_global);
572   retval = g_prgname;
573   G_UNLOCK (g_utils_global);
574
575   return retval;
576 }
577
578 void
579 g_set_prgname (const gchar *prgname)
580 {
581   gchar *c;
582     
583   G_LOCK (g_utils_global);
584   c = g_prgname;
585   g_prgname = g_strdup (prgname);
586   g_free (c);
587   G_UNLOCK (g_utils_global);
588 }
589
590 guint
591 g_direct_hash (gconstpointer v)
592 {
593   return GPOINTER_TO_UINT (v);
594 }
595
596 gint
597 g_direct_equal (gconstpointer v1,
598                 gconstpointer v2)
599 {
600   return GPOINTER_TO_UINT (v1) == GPOINTER_TO_UINT (v2);
601 }
602
603 gint
604 g_int_equal (gconstpointer v1,
605              gconstpointer v2)
606 {
607   return *((const gint*) v1) == *((const gint*) v2);
608 }
609
610 guint
611 g_int_hash (gconstpointer v)
612 {
613   return *(const gint*) v;
614 }
615
616 #if 0 /* Old IO Channels */
617
618 GIOChannel*
619 g_iochannel_new (gint fd)
620 {
621   GIOChannel *channel = g_new (GIOChannel, 1);
622
623   channel->fd = fd;
624
625 #ifdef NATIVE_WIN32
626   channel->peer = 0;
627   channel->peer_fd = 0;
628   channel->offset = 0;
629   channel->need_wakeups = 0;
630 #endif /* NATIVE_WIN32 */
631
632   return channel;
633 }
634
635 void
636 g_iochannel_free (GIOChannel *channel)
637 {
638   g_return_if_fail (channel != NULL);
639
640   g_free (channel);
641 }
642
643 void
644 g_iochannel_close_and_free (GIOChannel *channel)
645 {
646   g_return_if_fail (channel != NULL);
647
648   close (channel->fd);
649
650   g_iochannel_free (channel);
651 }
652
653 #undef g_iochannel_wakeup_peer
654
655 void
656 g_iochannel_wakeup_peer (GIOChannel *channel)
657 {
658 #ifdef NATIVE_WIN32
659   static guint message = 0;
660 #endif
661
662   g_return_if_fail (channel != NULL);
663
664 #ifdef NATIVE_WIN32
665   if (message == 0)
666     message = RegisterWindowMessage ("gdk-pipe-readable");
667
668 #  if 0
669   g_print ("g_iochannel_wakeup_peer: calling PostThreadMessage (%#x, %d, %d, %d)\n",
670            channel->peer, message, channel->peer_fd, channel->offset);
671 #  endif
672   PostThreadMessage (channel->peer, message,
673                      channel->peer_fd, channel->offset);
674 #endif /* NATIVE_WIN32 */
675 }
676
677 #endif /* Old IO Channels */
678
679 #ifdef NATIVE_WIN32
680 #ifdef _MSC_VER
681
682 int
683 gwin_ftruncate (gint  fd,
684                 guint size)
685 {
686   HANDLE hfile;
687   guint curpos;
688
689   g_return_val_if_fail (fd >= 0, -1);
690   
691   hfile = (HANDLE) _get_osfhandle (fd);
692   curpos = SetFilePointer (hfile, 0, NULL, FILE_CURRENT);
693   if (curpos == 0xFFFFFFFF
694       || SetFilePointer (hfile, size, NULL, FILE_BEGIN) == 0xFFFFFFFF
695       || !SetEndOfFile (hfile))
696     {
697       gint error = GetLastError ();
698
699       switch (error)
700         {
701         case ERROR_INVALID_HANDLE:
702           errno = EBADF;
703           break;
704         default:
705           errno = EIO;
706           break;
707         }
708
709       return -1;
710     }
711
712   return 0;
713 }
714
715 DIR*
716 gwin_opendir (const char *dirname)
717 {
718   DIR *result;
719   gchar *mask;
720   guint k;
721
722   g_return_val_if_fail (dirname != NULL, NULL);
723
724   result = g_new0 (DIR, 1);
725   result->find_file_data = g_new0 (WIN32_FIND_DATA, 1);
726   result->dir_name = g_strdup (dirname);
727   
728   k = strlen (result->dir_name);
729   if (k && result->dir_name[k - 1] == '\\')
730     {
731       result->dir_name[k - 1] = '\0';
732       k--;
733     }
734   mask = g_strdup_printf ("%s\\*", result->dir_name);
735
736   result->find_file_handle = (guint) FindFirstFile (mask,
737                                              (LPWIN32_FIND_DATA) result->find_file_data);
738   g_free (mask);
739
740   if (result->find_file_handle == (guint) INVALID_HANDLE_VALUE)
741     {
742       int error = GetLastError ();
743
744       g_free (result->dir_name);
745       g_free (result->find_file_data);
746       g_free (result);
747       switch (error)
748         {
749         default:
750           errno = EIO;
751           return NULL;
752         }
753     }
754   result->just_opened = TRUE;
755
756   return result;
757 }
758
759 struct dirent*
760 gwin_readdir (DIR *dir)
761 {
762   static struct dirent result;
763
764   g_return_val_if_fail (dir != NULL, NULL);
765
766   if (dir->just_opened)
767     dir->just_opened = FALSE;
768   else
769     {
770       if (!FindNextFile ((HANDLE) dir->find_file_handle,
771                          (LPWIN32_FIND_DATA) dir->find_file_data))
772         {
773           int error = GetLastError ();
774
775           switch (error)
776             {
777             case ERROR_NO_MORE_FILES:
778               return NULL;
779             default:
780               errno = EIO;
781               return NULL;
782             }
783         }
784     }
785   strcpy (result.d_name, g_basename (((LPWIN32_FIND_DATA) dir->find_file_data)->cFileName));
786       
787   return &result;
788 }
789
790 void
791 gwin_rewinddir (DIR *dir)
792 {
793   gchar *mask;
794
795   g_return_if_fail (dir != NULL);
796
797   if (!FindClose ((HANDLE) dir->find_file_handle))
798     g_warning ("gwin_rewinddir(): FindClose() failed\n");
799
800   mask = g_strdup_printf ("%s\\*", dir->dir_name);
801   dir->find_file_handle = (guint) FindFirstFile (mask,
802                                           (LPWIN32_FIND_DATA) dir->find_file_data);
803   g_free (mask);
804
805   if (dir->find_file_handle == (guint) INVALID_HANDLE_VALUE)
806     {
807       int error = GetLastError ();
808
809       switch (error)
810         {
811         default:
812           errno = EIO;
813           return;
814         }
815     }
816   dir->just_opened = TRUE;
817 }  
818
819 gint
820 gwin_closedir (DIR *dir)
821 {
822   g_return_val_if_fail (dir != NULL, -1);
823
824   if (!FindClose ((HANDLE) dir->find_file_handle))
825     {
826       int error = GetLastError ();
827
828       switch (error)
829         {
830         default:
831           errno = EIO; return -1;
832         }
833     }
834
835   g_free (dir->dir_name);
836   g_free (dir->find_file_data);
837   g_free (dir);
838
839   return 0;
840 }
841
842 #endif /* _MSC_VER */
843
844 #endif /* NATIVE_WIN32 */