Replace #ifdef HAVE_UNISTD_H checks with #ifdef G_OS_UNIX
[platform/upstream/glib.git] / glib / 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 #include "config.h"
32 #include "glibconfig.h"
33
34 #include <stdarg.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <locale.h>
38 #include <string.h>
39 #include <ctype.h>              /* For tolower() */
40 #include <errno.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #ifdef G_OS_UNIX
44 #include <pwd.h>
45 #include <unistd.h>
46 #endif
47 #include <sys/types.h>
48 #ifdef HAVE_SYS_PARAM_H
49 #include <sys/param.h>
50 #endif
51 #ifdef HAVE_CRT_EXTERNS_H 
52 #include <crt_externs.h> /* for _NSGetEnviron */
53 #endif
54
55 /* implement gutils's inline functions
56  */
57 #define G_IMPLEMENT_INLINES 1
58 #define __G_UTILS_C__
59 #include "gutils.h"
60
61 #include "glib-init.h"
62 #include "glib-private.h"
63 #include "genviron.h"
64 #include "gfileutils.h"
65 #include "ggettext.h"
66 #include "ghash.h"
67 #include "gthread.h"
68 #include "gtestutils.h"
69 #include "gunicode.h"
70 #include "gstrfuncs.h"
71 #include "garray.h"
72 #include "glibintl.h"
73
74 #ifdef G_PLATFORM_WIN32
75 #include "gconvert.h"
76 #include "gwin32.h"
77 #endif
78
79
80 /**
81  * SECTION:misc_utils
82  * @title: Miscellaneous Utility Functions
83  * @short_description: a selection of portable utility functions
84  *
85  * These are portable utility functions.
86  */
87
88 #ifdef G_PLATFORM_WIN32
89 #  include <windows.h>
90 #  ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
91 #    define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
92 #    define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
93 #  endif
94 #  include <lmcons.h>           /* For UNLEN */
95 #endif /* G_PLATFORM_WIN32 */
96
97 #ifdef G_OS_WIN32
98 #  include <direct.h>
99 #  include <shlobj.h>
100    /* older SDK (e.g. msvc 5.0) does not have these*/
101 #  ifndef CSIDL_MYMUSIC
102 #    define CSIDL_MYMUSIC 13
103 #  endif
104 #  ifndef CSIDL_MYVIDEO
105 #    define CSIDL_MYVIDEO 14
106 #  endif
107 #  ifndef CSIDL_INTERNET_CACHE
108 #    define CSIDL_INTERNET_CACHE 32
109 #  endif
110 #  ifndef CSIDL_COMMON_APPDATA
111 #    define CSIDL_COMMON_APPDATA 35
112 #  endif
113 #  ifndef CSIDL_MYPICTURES
114 #    define CSIDL_MYPICTURES 0x27
115 #  endif
116 #  ifndef CSIDL_COMMON_DOCUMENTS
117 #    define CSIDL_COMMON_DOCUMENTS 46
118 #  endif
119 #  ifndef CSIDL_PROFILE
120 #    define CSIDL_PROFILE 40
121 #  endif
122 #  include <process.h>
123 #endif
124
125 #ifdef HAVE_CARBON
126 #include <CoreServices/CoreServices.h>
127 #endif
128
129 #ifdef HAVE_CODESET
130 #include <langinfo.h>
131 #endif
132
133 #ifdef G_PLATFORM_WIN32
134
135 gchar *
136 _glib_get_dll_directory (void)
137 {
138   gchar *retval;
139   gchar *p;
140   wchar_t wc_fn[MAX_PATH];
141
142 #ifdef DLL_EXPORT
143   if (glib_dll == NULL)
144     return NULL;
145 #endif
146
147   /* This code is different from that in
148    * g_win32_get_package_installation_directory_of_module() in that
149    * here we return the actual folder where the GLib DLL is. We don't
150    * do the check for it being in a "bin" or "lib" subfolder and then
151    * returning the parent of that.
152    *
153    * In a statically built GLib, glib_dll will be NULL and we will
154    * thus look up the application's .exe file's location.
155    */
156   if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
157     return NULL;
158
159   retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
160
161   p = strrchr (retval, G_DIR_SEPARATOR);
162   if (p == NULL)
163     {
164       /* Wtf? */
165       return NULL;
166     }
167   *p = '\0';
168
169   return retval;
170 }
171
172 #endif
173
174 /**
175  * g_memmove: 
176  * @dest: the destination address to copy the bytes to.
177  * @src: the source address to copy the bytes from.
178  * @len: the number of bytes to copy.
179  *
180  * Copies a block of memory @len bytes long, from @src to @dest.
181  * The source and destination areas may overlap.
182  *
183  * Deprecated:2.40: Just use memmove().
184  */
185
186 #ifdef G_OS_WIN32
187 #undef g_atexit
188 #endif
189
190 /**
191  * g_atexit:
192  * @func: (scope async): the function to call on normal program termination.
193  * 
194  * Specifies a function to be called at normal program termination.
195  *
196  * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
197  * macro that maps to a call to the atexit() function in the C
198  * library. This means that in case the code that calls g_atexit(),
199  * i.e. atexit(), is in a DLL, the function will be called when the
200  * DLL is detached from the program. This typically makes more sense
201  * than that the function is called when the GLib DLL is detached,
202  * which happened earlier when g_atexit() was a function in the GLib
203  * DLL.
204  *
205  * The behaviour of atexit() in the context of dynamically loaded
206  * modules is not formally specified and varies wildly.
207  *
208  * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
209  * loaded module which is unloaded before the program terminates might
210  * well cause a crash at program exit.
211  *
212  * Some POSIX systems implement atexit() like Windows, and have each
213  * dynamically loaded module maintain an own atexit chain that is
214  * called when the module is unloaded.
215  *
216  * On other POSIX systems, before a dynamically loaded module is
217  * unloaded, the registered atexit functions (if any) residing in that
218  * module are called, regardless where the code that registered them
219  * resided. This is presumably the most robust approach.
220  *
221  * As can be seen from the above, for portability it's best to avoid
222  * calling g_atexit() (or atexit()) except in the main executable of a
223  * program.
224  *
225  * Deprecated:2.32: It is best to avoid g_atexit().
226  */
227 void
228 g_atexit (GVoidFunc func)
229 {
230   gint result;
231
232   result = atexit ((void (*)(void)) func);
233   if (result)
234     {
235       g_error ("Could not register atexit() function: %s",
236                g_strerror (errno));
237     }
238 }
239
240 /* Based on execvp() from GNU Libc.
241  * Some of this code is cut-and-pasted into gspawn.c
242  */
243
244 static gchar*
245 my_strchrnul (const gchar *str, 
246               gchar        c)
247 {
248   gchar *p = (gchar*)str;
249   while (*p && (*p != c))
250     ++p;
251
252   return p;
253 }
254
255 #ifdef G_OS_WIN32
256
257 static gchar *inner_find_program_in_path (const gchar *program);
258
259 gchar*
260 g_find_program_in_path (const gchar *program)
261 {
262   const gchar *last_dot = strrchr (program, '.');
263
264   if (last_dot == NULL ||
265       strchr (last_dot, '\\') != NULL ||
266       strchr (last_dot, '/') != NULL)
267     {
268       const gint program_length = strlen (program);
269       gchar *pathext = g_build_path (";",
270                                      ".exe;.cmd;.bat;.com",
271                                      g_getenv ("PATHEXT"),
272                                      NULL);
273       gchar *p;
274       gchar *decorated_program;
275       gchar *retval;
276
277       p = pathext;
278       do
279         {
280           gchar *q = my_strchrnul (p, ';');
281
282           decorated_program = g_malloc (program_length + (q-p) + 1);
283           memcpy (decorated_program, program, program_length);
284           memcpy (decorated_program+program_length, p, q-p);
285           decorated_program [program_length + (q-p)] = '\0';
286           
287           retval = inner_find_program_in_path (decorated_program);
288           g_free (decorated_program);
289
290           if (retval != NULL)
291             {
292               g_free (pathext);
293               return retval;
294             }
295           p = q;
296         } while (*p++ != '\0');
297       g_free (pathext);
298       return NULL;
299     }
300   else
301     return inner_find_program_in_path (program);
302 }
303
304 #endif
305
306 /**
307  * g_find_program_in_path:
308  * @program: a program name in the GLib file name encoding
309  * 
310  * Locates the first executable named @program in the user's path, in the
311  * same way that execvp() would locate it. Returns an allocated string
312  * with the absolute path name, or %NULL if the program is not found in
313  * the path. If @program is already an absolute path, returns a copy of
314  * @program if @program exists and is executable, and %NULL otherwise.
315  *  
316  * On Windows, if @program does not have a file type suffix, tries
317  * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
318  * the <envar>PATHEXT</envar> environment variable. 
319  * 
320  * On Windows, it looks for the file in the same way as CreateProcess() 
321  * would. This means first in the directory where the executing
322  * program was loaded from, then in the current directory, then in the
323  * Windows 32-bit system directory, then in the Windows directory, and
324  * finally in the directories in the <envar>PATH</envar> environment 
325  * variable. If the program is found, the return value contains the 
326  * full name including the type suffix.
327  *
328  * Return value: a newly-allocated string with the absolute path, or %NULL
329  **/
330 #ifdef G_OS_WIN32
331 static gchar *
332 inner_find_program_in_path (const gchar *program)
333 #else
334 gchar*
335 g_find_program_in_path (const gchar *program)
336 #endif
337 {
338   const gchar *path, *p;
339   gchar *name, *freeme;
340 #ifdef G_OS_WIN32
341   const gchar *path_copy;
342   gchar *filename = NULL, *appdir = NULL;
343   gchar *sysdir = NULL, *windir = NULL;
344   int n;
345   wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
346     wwindir[MAXPATHLEN];
347 #endif
348   gsize len;
349   gsize pathlen;
350
351   g_return_val_if_fail (program != NULL, NULL);
352
353   /* If it is an absolute path, or a relative path including subdirectories,
354    * don't look in PATH.
355    */
356   if (g_path_is_absolute (program)
357       || strchr (program, G_DIR_SEPARATOR) != NULL
358 #ifdef G_OS_WIN32
359       || strchr (program, '/') != NULL
360 #endif
361       )
362     {
363       if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
364           !g_file_test (program, G_FILE_TEST_IS_DIR))
365         return g_strdup (program);
366       else
367         return NULL;
368     }
369   
370   path = g_getenv ("PATH");
371 #if defined(G_OS_UNIX)
372   if (path == NULL)
373     {
374       /* There is no 'PATH' in the environment.  The default
375        * search path in GNU libc is the current directory followed by
376        * the path 'confstr' returns for '_CS_PATH'.
377        */
378       
379       /* In GLib we put . last, for security, and don't use the
380        * unportable confstr(); UNIX98 does not actually specify
381        * what to search if PATH is unset. POSIX may, dunno.
382        */
383       
384       path = "/bin:/usr/bin:.";
385     }
386 #else
387   n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
388   if (n > 0 && n < MAXPATHLEN)
389     filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
390   
391   n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
392   if (n > 0 && n < MAXPATHLEN)
393     sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
394   
395   n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
396   if (n > 0 && n < MAXPATHLEN)
397     windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
398   
399   if (filename)
400     {
401       appdir = g_path_get_dirname (filename);
402       g_free (filename);
403     }
404   
405   path = g_strdup (path);
406
407   if (windir)
408     {
409       const gchar *tem = path;
410       path = g_strconcat (windir, ";", path, NULL);
411       g_free ((gchar *) tem);
412       g_free (windir);
413     }
414   
415   if (sysdir)
416     {
417       const gchar *tem = path;
418       path = g_strconcat (sysdir, ";", path, NULL);
419       g_free ((gchar *) tem);
420       g_free (sysdir);
421     }
422   
423   {
424     const gchar *tem = path;
425     path = g_strconcat (".;", path, NULL);
426     g_free ((gchar *) tem);
427   }
428   
429   if (appdir)
430     {
431       const gchar *tem = path;
432       path = g_strconcat (appdir, ";", path, NULL);
433       g_free ((gchar *) tem);
434       g_free (appdir);
435     }
436
437   path_copy = path;
438 #endif
439   
440   len = strlen (program) + 1;
441   pathlen = strlen (path);
442   freeme = name = g_malloc (pathlen + len + 1);
443   
444   /* Copy the file name at the top, including '\0'  */
445   memcpy (name + pathlen + 1, program, len);
446   name = name + pathlen;
447   /* And add the slash before the filename  */
448   *name = G_DIR_SEPARATOR;
449   
450   p = path;
451   do
452     {
453       char *startp;
454
455       path = p;
456       p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
457
458       if (p == path)
459         /* Two adjacent colons, or a colon at the beginning or the end
460          * of 'PATH' means to search the current directory.
461          */
462         startp = name + 1;
463       else
464         startp = memcpy (name - (p - path), path, p - path);
465
466       if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
467           !g_file_test (startp, G_FILE_TEST_IS_DIR))
468         {
469           gchar *ret;
470           ret = g_strdup (startp);
471           g_free (freeme);
472 #ifdef G_OS_WIN32
473           g_free ((gchar *) path_copy);
474 #endif
475           return ret;
476         }
477     }
478   while (*p++ != '\0');
479   
480   g_free (freeme);
481 #ifdef G_OS_WIN32
482   g_free ((gchar *) path_copy);
483 #endif
484
485   return NULL;
486 }
487
488 /**
489  * g_bit_nth_lsf:
490  * @mask: a #gulong containing flags
491  * @nth_bit: the index of the bit to start the search from
492  *
493  * Find the position of the first bit set in @mask, searching
494  * from (but not including) @nth_bit upwards. Bits are numbered
495  * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
496  * usually). To start searching from the 0th bit, set @nth_bit to -1.
497  *
498  * Returns: the index of the first bit set which is higher than @nth_bit
499  */
500
501 /**
502  * g_bit_nth_msf:
503  * @mask: a #gulong containing flags
504  * @nth_bit: the index of the bit to start the search from
505  *
506  * Find the position of the first bit set in @mask, searching
507  * from (but not including) @nth_bit downwards. Bits are numbered
508  * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
509  * usually). To start searching from the last bit, set @nth_bit to
510  * -1 or GLIB_SIZEOF_LONG * 8.
511  *
512  * Returns: the index of the first bit set which is lower than @nth_bit
513  */
514
515 /**
516  * g_bit_storage:
517  * @number: a #guint
518  *
519  * Gets the number of bits used to hold @number,
520  * e.g. if @number is 4, 3 bits are needed.
521  *
522  * Returns: the number of bits used to hold @number
523  */
524
525 G_LOCK_DEFINE_STATIC (g_utils_global);
526
527 typedef struct
528 {
529   gchar *user_name;
530   gchar *real_name;
531   gchar *home_dir;
532 } UserDatabaseEntry;
533
534 static  gchar   *g_user_data_dir = NULL;
535 static  gchar  **g_system_data_dirs = NULL;
536 static  gchar   *g_user_cache_dir = NULL;
537 static  gchar   *g_user_config_dir = NULL;
538 static  gchar  **g_system_config_dirs = NULL;
539
540 static  gchar  **g_user_special_dirs = NULL;
541
542 /* fifteen minutes of fame for everybody */
543 #define G_USER_DIRS_EXPIRE      15 * 60
544
545 #ifdef G_OS_WIN32
546
547 static gchar *
548 get_special_folder (int csidl)
549 {
550   wchar_t path[MAX_PATH+1];
551   HRESULT hr;
552   LPITEMIDLIST pidl = NULL;
553   BOOL b;
554   gchar *retval = NULL;
555
556   hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
557   if (hr == S_OK)
558     {
559       b = SHGetPathFromIDListW (pidl, path);
560       if (b)
561         retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
562       CoTaskMemFree (pidl);
563     }
564   return retval;
565 }
566
567 static char *
568 get_windows_directory_root (void)
569 {
570   wchar_t wwindowsdir[MAX_PATH];
571
572   if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
573     {
574       /* Usually X:\Windows, but in terminal server environments
575        * might be an UNC path, AFAIK.
576        */
577       char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
578       char *p;
579
580       if (windowsdir == NULL)
581         return g_strdup ("C:\\");
582
583       p = (char *) g_path_skip_root (windowsdir);
584       if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
585         p--;
586       *p = '\0';
587       return windowsdir;
588     }
589   else
590     return g_strdup ("C:\\");
591 }
592
593 #endif
594
595 /* HOLDS: g_utils_global_lock */
596 static UserDatabaseEntry *
597 g_get_user_database_entry (void)
598 {
599   static UserDatabaseEntry *entry;
600
601   if (g_once_init_enter (&entry))
602     {
603       static UserDatabaseEntry e;
604
605 #ifdef G_OS_UNIX
606       {
607         struct passwd *pw = NULL;
608         gpointer buffer = NULL;
609         gint error;
610         gchar *logname;
611
612 #  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
613         struct passwd pwd;
614 #    ifdef _SC_GETPW_R_SIZE_MAX
615         /* This reurns the maximum length */
616         glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
617
618         if (bufsize < 0)
619           bufsize = 64;
620 #    else /* _SC_GETPW_R_SIZE_MAX */
621         glong bufsize = 64;
622 #    endif /* _SC_GETPW_R_SIZE_MAX */
623
624         logname = (gchar *) g_getenv ("LOGNAME");
625
626         do
627           {
628             g_free (buffer);
629             /* we allocate 6 extra bytes to work around a bug in
630              * Mac OS < 10.3. See #156446
631              */
632             buffer = g_malloc (bufsize + 6);
633             errno = 0;
634
635 #    ifdef HAVE_POSIX_GETPWUID_R
636             if (logname) {
637               error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
638               if (!pw || (pw->pw_uid != getuid ())) {
639                 /* LOGNAME is lying, fall back to looking up the uid */
640                 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
641               }
642             } else {
643               error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
644             }
645             error = error < 0 ? errno : error;
646 #    else /* HAVE_NONPOSIX_GETPWUID_R */
647 #      if defined(_AIX)
648             error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
649             pw = error == 0 ? &pwd : NULL;
650 #      else /* !_AIX */
651             if (logname) {
652               pw = getpwnam_r (logname, &pwd, buffer, bufsize);
653               if (!pw || (pw->pw_uid != getuid ())) {
654                 /* LOGNAME is lying, fall back to looking up the uid */
655                 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
656               }
657             } else {
658               pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
659             }
660             error = pw ? 0 : errno;
661 #      endif /* !_AIX */
662 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
663
664             if (!pw)
665               {
666                 /* we bail out prematurely if the user id can't be found
667                  * (should be pretty rare case actually), or if the buffer
668                  * should be sufficiently big and lookups are still not
669                  * successful.
670                  */
671                 if (error == 0 || error == ENOENT)
672                   {
673                     g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
674                                (gulong) getuid ());
675                     break;
676                   }
677                 if (bufsize > 32 * 1024)
678                   {
679                     g_warning ("getpwuid_r(): failed due to: %s.",
680                                g_strerror (error));
681                     break;
682                   }
683
684                 bufsize *= 2;
685               }
686           }
687         while (!pw);
688 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
689
690         if (!pw)
691           {
692             pw = getpwuid (getuid ());
693           }
694         if (pw)
695           {
696             e.user_name = g_strdup (pw->pw_name);
697
698 #ifndef __BIONIC__
699             if (pw->pw_gecos && *pw->pw_gecos != '\0')
700               {
701                 gchar **gecos_fields;
702                 gchar **name_parts;
703
704                 /* split the gecos field and substitute '&' */
705                 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
706                 name_parts = g_strsplit (gecos_fields[0], "&", 0);
707                 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
708                 e.real_name = g_strjoinv (pw->pw_name, name_parts);
709                 g_strfreev (gecos_fields);
710                 g_strfreev (name_parts);
711               }
712 #endif
713
714             if (!e.home_dir)
715               e.home_dir = g_strdup (pw->pw_dir);
716           }
717         g_free (buffer);
718       }
719
720 #endif /* G_OS_UNIX */
721
722 #ifdef G_OS_WIN32
723       {
724         guint len = UNLEN+1;
725         wchar_t buffer[UNLEN+1];
726
727         if (GetUserNameW (buffer, (LPDWORD) &len))
728           {
729             e.user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
730             e.real_name = g_strdup (e.user_name);
731           }
732       }
733 #endif /* G_OS_WIN32 */
734
735       if (!e.user_name)
736         e.user_name = g_strdup ("somebody");
737       if (!e.real_name)
738         e.real_name = g_strdup ("Unknown");
739
740       g_once_init_leave (&entry, &e);
741     }
742
743   return entry;
744 }
745
746 /**
747  * g_get_user_name:
748  *
749  * Gets the user name of the current user. The encoding of the returned
750  * string is system-defined. On UNIX, it might be the preferred file name
751  * encoding, or something else, and there is no guarantee that it is even
752  * consistent on a machine. On Windows, it is always UTF-8.
753  *
754  * Returns: the user name of the current user.
755  */
756 const gchar *
757 g_get_user_name (void)
758 {
759   UserDatabaseEntry *entry;
760
761   entry = g_get_user_database_entry ();
762
763   return entry->user_name;
764 }
765
766 /**
767  * g_get_real_name:
768  *
769  * Gets the real name of the user. This usually comes from the user's entry 
770  * in the <filename>passwd</filename> file. The encoding of the returned 
771  * string is system-defined. (On Windows, it is, however, always UTF-8.) 
772  * If the real user name cannot be determined, the string "Unknown" is 
773  * returned.
774  *
775  * Returns: the user's real name.
776  */
777 const gchar *
778 g_get_real_name (void)
779 {
780   UserDatabaseEntry *entry;
781
782   entry = g_get_user_database_entry ();
783
784   return entry->real_name;
785 }
786
787 /**
788  * g_get_home_dir:
789  *
790  * Gets the current user's home directory.
791  *
792  * As with most UNIX tools, this function will return the value of the
793  * <envar>HOME</envar> environment variable if it is set to an existing
794  * absolute path name, falling back to the <filename>passwd</filename>
795  * file in the case that it is unset.
796  *
797  * If the path given in <envar>HOME</envar> is non-absolute, does not
798  * exist, or is not a directory, the result is undefined.
799  *
800  * <note><para>
801  *   Before version 2.36 this function would ignore the
802  *   <envar>HOME</envar> environment variable, taking the value from the
803  *   <filename>passwd</filename> database instead.  This was changed to
804  *   increase the compatibility of GLib with other programs (and the XDG
805  *   basedir specification) and to increase testability of programs
806  *   based on GLib (by making it easier to run them from test
807  *   frameworks).
808  * </para><para>
809  *   If your program has a strong requirement for either the new or the
810  *   old behaviour (and if you don't wish to increase your GLib
811  *   dependency to ensure that the new behaviour is in effect) then you
812  *   should either directly check the <envar>HOME</envar> environment
813  *   variable yourself or unset it before calling any functions in GLib.
814  * </para></note>
815  *
816  * Returns: the current user's home directory
817  */
818 const gchar *
819 g_get_home_dir (void)
820 {
821   static gchar *home_dir;
822
823   if (g_once_init_enter (&home_dir))
824     {
825       gchar *tmp;
826
827       /* We first check HOME and use it if it is set */
828       tmp = g_strdup (g_getenv ("HOME"));
829
830 #ifdef G_OS_WIN32
831       /* Only believe HOME if it is an absolute path and exists.
832        *
833        * We only do this check on Windows for a couple of reasons.
834        * Historically, we only did it there because we used to ignore $HOME
835        * on UNIX.  There are concerns about enabling it now on UNIX because
836        * of things like autofs.  In short, if the user has a bogus value in
837        * $HOME then they get what they pay for...
838        */
839       if (tmp)
840         {
841           if (!(g_path_is_absolute (tmp) &&
842                 g_file_test (tmp, G_FILE_TEST_IS_DIR)))
843             {
844               g_free (tmp);
845               tmp = NULL;
846             }
847         }
848
849       /* In case HOME is Unix-style (it happens), convert it to
850        * Windows style.
851        */
852       if (tmp)
853         {
854           gchar *p;
855           while ((p = strchr (tmp, '/')) != NULL)
856             *p = '\\';
857         }
858
859       if (!tmp)
860         {
861           /* USERPROFILE is probably the closest equivalent to $HOME? */
862           if (g_getenv ("USERPROFILE") != NULL)
863             tmp = g_strdup (g_getenv ("USERPROFILE"));
864         }
865
866       if (!tmp)
867         tmp = get_special_folder (CSIDL_PROFILE);
868
869       if (!tmp)
870         tmp = get_windows_directory_root ();
871 #endif /* G_OS_WIN32 */
872
873       if (!tmp)
874         {
875           /* If we didn't get it from any of those methods, we will have
876            * to read the user database entry.
877            */
878           UserDatabaseEntry *entry;
879
880           entry = g_get_user_database_entry ();
881
882           /* Strictly speaking, we should copy this, but we know that
883            * neither will ever be freed, so don't bother...
884            */
885           tmp = entry->home_dir;
886         }
887
888       g_once_init_leave (&home_dir, tmp);
889     }
890
891   return home_dir;
892 }
893
894 /**
895  * g_get_tmp_dir:
896  *
897  * Gets the directory to use for temporary files.
898  *
899  * On UNIX, this is taken from the <envar>TMPDIR</envar> environment
900  * variable.  If the variable is not set, <literal>P_tmpdir</literal> is
901  * used, as defined by the system C library.  Failing that, a hard-coded
902  * default of "/tmp" is returned.
903  *
904  * On Windows, the <envar>TEMP</envar> environment variable is used,
905  * with the root directory of the Windows installation (eg: "C:\") used
906  * as a default.
907  *
908  * The encoding of the returned string is system-defined. On Windows, it
909  * is always UTF-8. The return value is never %NULL or the empty string.
910  *
911  * Returns: the directory to use for temporary files.
912  */
913 const gchar *
914 g_get_tmp_dir (void)
915 {
916   static gchar *tmp_dir;
917
918   if (g_once_init_enter (&tmp_dir))
919     {
920       gchar *tmp;
921
922 #ifdef G_OS_WIN32
923       tmp = g_strdup (g_getenv ("TEMP"));
924
925       if (tmp == NULL || *tmp == '\0')
926         {
927           g_free (tmp);
928           tmp = get_windows_directory_root ();
929         }
930 #else /* G_OS_WIN32 */
931       tmp = g_strdup (g_getenv ("TMPDIR"));
932
933 #ifdef P_tmpdir
934       if (tmp == NULL || *tmp == '\0')
935         {
936           gsize k;
937           g_free (tmp);
938           tmp = g_strdup (P_tmpdir);
939           k = strlen (tmp);
940           if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
941             tmp[k - 1] = '\0';
942         }
943 #endif /* P_tmpdir */
944
945       if (tmp == NULL || *tmp == '\0')
946         {
947           g_free (tmp);
948           tmp = g_strdup ("/tmp");
949         }
950 #endif /* !G_OS_WIN32 */
951
952       g_once_init_leave (&tmp_dir, tmp);
953     }
954
955   return tmp_dir;
956 }
957
958 /**
959  * g_get_host_name:
960  *
961  * Return a name for the machine. 
962  *
963  * The returned name is not necessarily a fully-qualified domain name,
964  * or even present in DNS or some other name service at all. It need
965  * not even be unique on your local network or site, but usually it
966  * is. Callers should not rely on the return value having any specific
967  * properties like uniqueness for security purposes. Even if the name
968  * of the machine is changed while an application is running, the
969  * return value from this function does not change. The returned
970  * string is owned by GLib and should not be modified or freed. If no
971  * name can be determined, a default fixed string "localhost" is
972  * returned.
973  *
974  * Returns: the host name of the machine.
975  *
976  * Since: 2.8
977  */
978 const gchar *
979 g_get_host_name (void)
980 {
981   static gchar *hostname;
982
983   if (g_once_init_enter (&hostname))
984     {
985       gboolean failed;
986       gchar tmp[100];
987
988 #ifndef G_OS_WIN32
989       failed = (gethostname (tmp, sizeof (tmp)) == -1);
990 #else
991       DWORD size = sizeof (tmp);
992       failed = (!GetComputerName (tmp, &size));
993 #endif
994
995       g_once_init_leave (&hostname, g_strdup (failed ? "localhost" : tmp));
996     }
997
998   return hostname;
999 }
1000
1001 G_LOCK_DEFINE_STATIC (g_prgname);
1002 static gchar *g_prgname = NULL;
1003
1004 /**
1005  * g_get_prgname:
1006  *
1007  * Gets the name of the program. This name should <emphasis>not</emphasis> 
1008  * be localized, contrast with g_get_application_name().
1009  * (If you are using GDK or GTK+ the program name is set in gdk_init(), 
1010  * which is called by gtk_init(). The program name is found by taking 
1011  * the last component of <literal>argv[0]</literal>.)
1012  *
1013  * Returns: the name of the program. The returned string belongs 
1014  * to GLib and must not be modified or freed.
1015  */
1016 const gchar*
1017 g_get_prgname (void)
1018 {
1019   gchar* retval;
1020
1021   G_LOCK (g_prgname);
1022 #ifdef G_OS_WIN32
1023   if (g_prgname == NULL)
1024     {
1025       static gboolean beenhere = FALSE;
1026
1027       if (!beenhere)
1028         {
1029           gchar *utf8_buf = NULL;
1030           wchar_t buf[MAX_PATH+1];
1031
1032           beenhere = TRUE;
1033           if (GetModuleFileNameW (GetModuleHandle (NULL),
1034                                   buf, G_N_ELEMENTS (buf)) > 0)
1035             utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1036
1037           if (utf8_buf)
1038             {
1039               g_prgname = g_path_get_basename (utf8_buf);
1040               g_free (utf8_buf);
1041             }
1042         }
1043     }
1044 #endif
1045   retval = g_prgname;
1046   G_UNLOCK (g_prgname);
1047
1048   return retval;
1049 }
1050
1051 /**
1052  * g_set_prgname:
1053  * @prgname: the name of the program.
1054  *
1055  * Sets the name of the program. This name should <emphasis>not</emphasis> 
1056  * be localized, contrast with g_set_application_name(). Note that for 
1057  * thread-safety reasons this function can only be called once.
1058  */
1059 void
1060 g_set_prgname (const gchar *prgname)
1061 {
1062   G_LOCK (g_prgname);
1063   g_free (g_prgname);
1064   g_prgname = g_strdup (prgname);
1065   G_UNLOCK (g_prgname);
1066 }
1067
1068 G_LOCK_DEFINE_STATIC (g_application_name);
1069 static gchar *g_application_name = NULL;
1070
1071 /**
1072  * g_get_application_name:
1073  * 
1074  * Gets a human-readable name for the application, as set by
1075  * g_set_application_name(). This name should be localized if
1076  * possible, and is intended for display to the user.  Contrast with
1077  * g_get_prgname(), which gets a non-localized name. If
1078  * g_set_application_name() has not been called, returns the result of
1079  * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1080  * been called).
1081  * 
1082  * Return value: human-readable application name. may return %NULL
1083  *
1084  * Since: 2.2
1085  **/
1086 const gchar *
1087 g_get_application_name (void)
1088 {
1089   gchar* retval;
1090
1091   G_LOCK (g_application_name);
1092   retval = g_application_name;
1093   G_UNLOCK (g_application_name);
1094
1095   if (retval == NULL)
1096     return g_get_prgname ();
1097   
1098   return retval;
1099 }
1100
1101 /**
1102  * g_set_application_name:
1103  * @application_name: localized name of the application
1104  *
1105  * Sets a human-readable name for the application. This name should be
1106  * localized if possible, and is intended for display to the user.
1107  * Contrast with g_set_prgname(), which sets a non-localized name.
1108  * g_set_prgname() will be called automatically by gtk_init(),
1109  * but g_set_application_name() will not.
1110  *
1111  * Note that for thread safety reasons, this function can only
1112  * be called once.
1113  *
1114  * The application name will be used in contexts such as error messages,
1115  * or when displaying an application's name in the task list.
1116  * 
1117  * Since: 2.2
1118  **/
1119 void
1120 g_set_application_name (const gchar *application_name)
1121 {
1122   gboolean already_set = FALSE;
1123         
1124   G_LOCK (g_application_name);
1125   if (g_application_name)
1126     already_set = TRUE;
1127   else
1128     g_application_name = g_strdup (application_name);
1129   G_UNLOCK (g_application_name);
1130
1131   if (already_set)
1132     g_warning ("g_set_application_name() called multiple times");
1133 }
1134
1135 /**
1136  * g_get_user_data_dir:
1137  * 
1138  * Returns a base directory in which to access application data such
1139  * as icons that is customized for a particular user.  
1140  *
1141  * On UNIX platforms this is determined using the mechanisms described in
1142  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1143  * XDG Base Directory Specification</ulink>.
1144  * In this case the directory retrieved will be XDG_DATA_HOME.
1145  *
1146  * On Windows this is the folder to use for local (as opposed to
1147  * roaming) application data. See documentation for
1148  * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1149  * what g_get_user_config_dir() returns.
1150  *
1151  * Return value: a string owned by GLib that must not be modified 
1152  *               or freed.
1153  * Since: 2.6
1154  **/
1155 const gchar *
1156 g_get_user_data_dir (void)
1157 {
1158   gchar *data_dir;  
1159
1160   G_LOCK (g_utils_global);
1161
1162   if (!g_user_data_dir)
1163     {
1164 #ifdef G_OS_WIN32
1165       data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1166 #else
1167       data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1168
1169       if (data_dir && data_dir[0])
1170         data_dir = g_strdup (data_dir);
1171 #endif
1172       if (!data_dir || !data_dir[0])
1173         {
1174           const gchar *home_dir = g_get_home_dir ();
1175
1176           if (home_dir)
1177             data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1178           else
1179             data_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".local", "share", NULL);
1180         }
1181
1182       g_user_data_dir = data_dir;
1183     }
1184   else
1185     data_dir = g_user_data_dir;
1186
1187   G_UNLOCK (g_utils_global);
1188
1189   return data_dir;
1190 }
1191
1192 static void
1193 g_init_user_config_dir (void)
1194 {
1195   gchar *config_dir;
1196
1197   if (!g_user_config_dir)
1198     {
1199 #ifdef G_OS_WIN32
1200       config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1201 #else
1202       config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1203
1204       if (config_dir && config_dir[0])
1205         config_dir = g_strdup (config_dir);
1206 #endif
1207       if (!config_dir || !config_dir[0])
1208         {
1209           const gchar *home_dir = g_get_home_dir ();
1210
1211           if (home_dir)
1212             config_dir = g_build_filename (home_dir, ".config", NULL);
1213           else
1214             config_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".config", NULL);
1215         }
1216
1217       g_user_config_dir = config_dir;
1218     }
1219 }
1220
1221 /**
1222  * g_get_user_config_dir:
1223  * 
1224  * Returns a base directory in which to store user-specific application 
1225  * configuration information such as user preferences and settings. 
1226  *
1227  * On UNIX platforms this is determined using the mechanisms described in
1228  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1229  * XDG Base Directory Specification</ulink>.
1230  * In this case the directory retrieved will be XDG_CONFIG_HOME.
1231  *
1232  * On Windows this is the folder to use for local (as opposed to
1233  * roaming) application data. See documentation for
1234  * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1235  * what g_get_user_data_dir() returns.
1236  *
1237  * Return value: a string owned by GLib that must not be modified 
1238  *               or freed.
1239  * Since: 2.6
1240  **/
1241 const gchar *
1242 g_get_user_config_dir (void)
1243 {
1244   G_LOCK (g_utils_global);
1245
1246   g_init_user_config_dir ();
1247
1248   G_UNLOCK (g_utils_global);
1249
1250   return g_user_config_dir;
1251 }
1252
1253 /**
1254  * g_get_user_cache_dir:
1255  * 
1256  * Returns a base directory in which to store non-essential, cached
1257  * data specific to particular user.
1258  *
1259  * On UNIX platforms this is determined using the mechanisms described in
1260  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1261  * XDG Base Directory Specification</ulink>.
1262  * In this case the directory retrieved will be XDG_CACHE_HOME.
1263  *
1264  * On Windows is the directory that serves as a common repository for
1265  * temporary Internet files. A typical path is
1266  * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1267  * See documentation for CSIDL_INTERNET_CACHE.
1268  *
1269  * Return value: a string owned by GLib that must not be modified 
1270  *               or freed.
1271  * Since: 2.6
1272  **/
1273 const gchar *
1274 g_get_user_cache_dir (void)
1275 {
1276   gchar *cache_dir;  
1277
1278   G_LOCK (g_utils_global);
1279
1280   if (!g_user_cache_dir)
1281     {
1282 #ifdef G_OS_WIN32
1283       cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1284 #else
1285       cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1286
1287       if (cache_dir && cache_dir[0])
1288           cache_dir = g_strdup (cache_dir);
1289 #endif
1290       if (!cache_dir || !cache_dir[0])
1291         {
1292           const gchar *home_dir = g_get_home_dir ();
1293
1294           if (home_dir)
1295             cache_dir = g_build_filename (home_dir, ".cache", NULL);
1296           else
1297             cache_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".cache", NULL);
1298         }
1299       g_user_cache_dir = cache_dir;
1300     }
1301   else
1302     cache_dir = g_user_cache_dir;
1303
1304   G_UNLOCK (g_utils_global);
1305
1306   return cache_dir;
1307 }
1308
1309 /**
1310  * g_get_user_runtime_dir:
1311  *
1312  * Returns a directory that is unique to the current user on the local
1313  * system.
1314  *
1315  * On UNIX platforms this is determined using the mechanisms described in
1316  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1317  * XDG Base Directory Specification</ulink>.  This is the directory
1318  * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
1319  * In the case that this variable is not set, GLib will issue a warning
1320  * message to stderr and return the value of g_get_user_cache_dir().
1321  *
1322  * On Windows this is the folder to use for local (as opposed to
1323  * roaming) application data. See documentation for
1324  * CSIDL_LOCAL_APPDATA.  Note that on Windows it thus is the same as
1325  * what g_get_user_config_dir() returns.
1326  *
1327  * Returns: a string owned by GLib that must not be modified or freed.
1328  *
1329  * Since: 2.28
1330  **/
1331 const gchar *
1332 g_get_user_runtime_dir (void)
1333 {
1334 #ifndef G_OS_WIN32
1335   static const gchar *runtime_dir;
1336   static gsize initialised;
1337
1338   if (g_once_init_enter (&initialised))
1339     {
1340       runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1341       
1342       g_once_init_leave (&initialised, 1);
1343     }
1344
1345   if (runtime_dir)
1346     return runtime_dir;
1347
1348   /* Both fallback for UNIX and the default
1349    * in Windows: use the user cache directory.
1350    */
1351 #endif
1352
1353   return g_get_user_cache_dir ();
1354 }
1355
1356 #ifdef HAVE_CARBON
1357
1358 static gchar *
1359 find_folder (OSType type)
1360 {
1361   gchar *filename = NULL;
1362   FSRef  found;
1363
1364   if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1365     {
1366       CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1367
1368       if (url)
1369         {
1370           CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1371
1372           if (path)
1373             {
1374               filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1375
1376               if (! filename)
1377                 {
1378                   filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1379
1380                   CFStringGetCString (path, filename,
1381                                       CFStringGetLength (path) * 3 + 1,
1382                                       kCFStringEncodingUTF8);
1383                 }
1384
1385               CFRelease (path);
1386             }
1387
1388           CFRelease (url);
1389         }
1390     }
1391
1392   return filename;
1393 }
1394
1395 static void
1396 load_user_special_dirs (void)
1397 {
1398   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1399   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1400   g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1401   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1402   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1403   g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1404   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1405   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1406 }
1407
1408 #endif /* HAVE_CARBON */
1409
1410 #if defined(G_OS_WIN32)
1411 static void
1412 load_user_special_dirs (void)
1413 {
1414   typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1415                                                     DWORD dwFlags,
1416                                                     HANDLE hToken,
1417                                                     PWSTR *ppszPath);
1418   t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1419
1420   static const GUID FOLDERID_Downloads =
1421     { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1422   static const GUID FOLDERID_Public =
1423     { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1424
1425   wchar_t *wcp;
1426
1427   p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1428                                                                     "SHGetKnownFolderPath");
1429
1430   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1431   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1432
1433   if (p_SHGetKnownFolderPath == NULL)
1434     {
1435       g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1436     }
1437   else
1438     {
1439       wcp = NULL;
1440       (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1441       if (wcp)
1442         {
1443           g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1444           if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1445               g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1446           CoTaskMemFree (wcp);
1447         }
1448       else
1449           g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1450     }
1451
1452   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1453   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1454
1455   if (p_SHGetKnownFolderPath == NULL)
1456     {
1457       /* XXX */
1458       g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1459     }
1460   else
1461     {
1462       wcp = NULL;
1463       (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1464       if (wcp)
1465         {
1466           g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1467           if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1468               g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1469           CoTaskMemFree (wcp);
1470         }
1471       else
1472           g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1473     }
1474   
1475   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1476   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1477 }
1478 #endif /* G_OS_WIN32 */
1479
1480
1481 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
1482
1483 /* adapted from xdg-user-dir-lookup.c
1484  *
1485  * Copyright (C) 2007 Red Hat Inc.
1486  *
1487  * Permission is hereby granted, free of charge, to any person
1488  * obtaining a copy of this software and associated documentation files
1489  * (the "Software"), to deal in the Software without restriction,
1490  * including without limitation the rights to use, copy, modify, merge,
1491  * publish, distribute, sublicense, and/or sell copies of the Software,
1492  * and to permit persons to whom the Software is furnished to do so,
1493  * subject to the following conditions: 
1494  *
1495  * The above copyright notice and this permission notice shall be
1496  * included in all copies or substantial portions of the Software. 
1497  *
1498  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1499  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1500  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1501  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1502  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1503  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1504  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1505  * SOFTWARE.
1506  */
1507 static void
1508 load_user_special_dirs (void)
1509 {
1510   gchar *config_file;
1511   gchar *data;
1512   gchar **lines;
1513   gint n_lines, i;
1514   
1515   g_init_user_config_dir ();
1516   config_file = g_build_filename (g_user_config_dir,
1517                                   "user-dirs.dirs",
1518                                   NULL);
1519   
1520   if (!g_file_get_contents (config_file, &data, NULL, NULL))
1521     {
1522       g_free (config_file);
1523       return;
1524     }
1525
1526   lines = g_strsplit (data, "\n", -1);
1527   n_lines = g_strv_length (lines);
1528   g_free (data);
1529   
1530   for (i = 0; i < n_lines; i++)
1531     {
1532       gchar *buffer = lines[i];
1533       gchar *d, *p;
1534       gint len;
1535       gboolean is_relative = FALSE;
1536       GUserDirectory directory;
1537
1538       /* Remove newline at end */
1539       len = strlen (buffer);
1540       if (len > 0 && buffer[len - 1] == '\n')
1541         buffer[len - 1] = 0;
1542       
1543       p = buffer;
1544       while (*p == ' ' || *p == '\t')
1545         p++;
1546       
1547       if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1548         {
1549           directory = G_USER_DIRECTORY_DESKTOP;
1550           p += strlen ("XDG_DESKTOP_DIR");
1551         }
1552       else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1553         {
1554           directory = G_USER_DIRECTORY_DOCUMENTS;
1555           p += strlen ("XDG_DOCUMENTS_DIR");
1556         }
1557       else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1558         {
1559           directory = G_USER_DIRECTORY_DOWNLOAD;
1560           p += strlen ("XDG_DOWNLOAD_DIR");
1561         }
1562       else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1563         {
1564           directory = G_USER_DIRECTORY_MUSIC;
1565           p += strlen ("XDG_MUSIC_DIR");
1566         }
1567       else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1568         {
1569           directory = G_USER_DIRECTORY_PICTURES;
1570           p += strlen ("XDG_PICTURES_DIR");
1571         }
1572       else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1573         {
1574           directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1575           p += strlen ("XDG_PUBLICSHARE_DIR");
1576         }
1577       else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1578         {
1579           directory = G_USER_DIRECTORY_TEMPLATES;
1580           p += strlen ("XDG_TEMPLATES_DIR");
1581         }
1582       else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1583         {
1584           directory = G_USER_DIRECTORY_VIDEOS;
1585           p += strlen ("XDG_VIDEOS_DIR");
1586         }
1587       else
1588         continue;
1589
1590       while (*p == ' ' || *p == '\t')
1591         p++;
1592
1593       if (*p != '=')
1594         continue;
1595       p++;
1596
1597       while (*p == ' ' || *p == '\t')
1598         p++;
1599
1600       if (*p != '"')
1601         continue;
1602       p++;
1603
1604       if (strncmp (p, "$HOME", 5) == 0)
1605         {
1606           p += 5;
1607           is_relative = TRUE;
1608         }
1609       else if (*p != '/')
1610         continue;
1611
1612       d = strrchr (p, '"');
1613       if (!d)
1614         continue;
1615       *d = 0;
1616
1617       d = p;
1618       
1619       /* remove trailing slashes */
1620       len = strlen (d);
1621       if (d[len - 1] == '/')
1622         d[len - 1] = 0;
1623       
1624       if (is_relative)
1625         {
1626           g_user_special_dirs[directory] = g_build_filename (g_get_home_dir (), d, NULL);
1627         }
1628       else
1629         g_user_special_dirs[directory] = g_strdup (d);
1630     }
1631
1632   g_strfreev (lines);
1633   g_free (config_file);
1634 }
1635
1636 #endif /* G_OS_UNIX && !HAVE_CARBON */
1637
1638
1639 /**
1640  * g_reload_user_special_dirs_cache:
1641  *
1642  * Resets the cache used for g_get_user_special_dir(), so
1643  * that the latest on-disk version is used. Call this only
1644  * if you just changed the data on disk yourself.
1645  *
1646  * Due to threadsafety issues this may cause leaking of strings
1647  * that were previously returned from g_get_user_special_dir()
1648  * that can't be freed. We ensure to only leak the data for
1649  * the directories that actually changed value though.
1650  *
1651  * Since: 2.22
1652  */
1653 void
1654 g_reload_user_special_dirs_cache (void)
1655 {
1656   int i;
1657
1658   G_LOCK (g_utils_global);
1659
1660   if (g_user_special_dirs != NULL)
1661     {
1662       /* save a copy of the pointer, to check if some memory can be preserved */
1663       char **old_g_user_special_dirs = g_user_special_dirs;
1664       char *old_val;
1665
1666       /* recreate and reload our cache */
1667       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1668       load_user_special_dirs ();
1669
1670       /* only leak changed directories */
1671       for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1672         {
1673           old_val = old_g_user_special_dirs[i];
1674           if (g_user_special_dirs[i] == NULL)
1675             {
1676               g_user_special_dirs[i] = old_val;
1677             }
1678           else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1679             {
1680               /* don't leak */
1681               g_free (g_user_special_dirs[i]);
1682               g_user_special_dirs[i] = old_val;
1683             }
1684           else
1685             g_free (old_val);
1686         }
1687
1688       /* free the old array */
1689       g_free (old_g_user_special_dirs);
1690     }
1691
1692   G_UNLOCK (g_utils_global);
1693 }
1694
1695 /**
1696  * g_get_user_special_dir:
1697  * @directory: the logical id of special directory
1698  *
1699  * Returns the full path of a special directory using its logical id.
1700  *
1701  * On Unix this is done using the XDG special user directories.
1702  * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1703  * falls back to <filename>$HOME/Desktop</filename> when XDG special
1704  * user directories have not been set up. 
1705  *
1706  * Depending on the platform, the user might be able to change the path
1707  * of the special directory without requiring the session to restart; GLib
1708  * will not reflect any change once the special directories are loaded.
1709  *
1710  * Return value: the path to the specified special directory, or %NULL
1711  *   if the logical id was not found. The returned string is owned by
1712  *   GLib and should not be modified or freed.
1713  *
1714  * Since: 2.14
1715  */
1716 const gchar *
1717 g_get_user_special_dir (GUserDirectory directory)
1718 {
1719   g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1720                         directory < G_USER_N_DIRECTORIES, NULL);
1721
1722   G_LOCK (g_utils_global);
1723
1724   if (G_UNLIKELY (g_user_special_dirs == NULL))
1725     {
1726       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1727
1728       load_user_special_dirs ();
1729
1730       /* Special-case desktop for historical compatibility */
1731       if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1732         g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (g_get_home_dir (), "Desktop", NULL);
1733     }
1734
1735   G_UNLOCK (g_utils_global);
1736
1737   return g_user_special_dirs[directory];
1738 }
1739
1740 #ifdef G_OS_WIN32
1741
1742 #undef g_get_system_data_dirs
1743
1744 static HMODULE
1745 get_module_for_address (gconstpointer address)
1746 {
1747   /* Holds the g_utils_global lock */
1748
1749   static gboolean beenhere = FALSE;
1750   typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1751   static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1752   HMODULE hmodule = NULL;
1753
1754   if (!address)
1755     return NULL;
1756
1757   if (!beenhere)
1758     {
1759       p_GetModuleHandleExA =
1760         (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1761                                                "GetModuleHandleExA");
1762       beenhere = TRUE;
1763     }
1764
1765   if (p_GetModuleHandleExA == NULL ||
1766       !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1767                                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1768                                 address, &hmodule))
1769     {
1770       MEMORY_BASIC_INFORMATION mbi;
1771       VirtualQuery (address, &mbi, sizeof (mbi));
1772       hmodule = (HMODULE) mbi.AllocationBase;
1773     }
1774
1775   return hmodule;
1776 }
1777
1778 static gchar *
1779 get_module_share_dir (gconstpointer address)
1780 {
1781   HMODULE hmodule;
1782   gchar *filename;
1783   gchar *retval;
1784
1785   hmodule = get_module_for_address (address);
1786   if (hmodule == NULL)
1787     return NULL;
1788
1789   filename = g_win32_get_package_installation_directory_of_module (hmodule);
1790   retval = g_build_filename (filename, "share", NULL);
1791   g_free (filename);
1792
1793   return retval;
1794 }
1795
1796 const gchar * const *
1797 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
1798 {
1799   GArray *data_dirs;
1800   HMODULE hmodule;
1801   static GHashTable *per_module_data_dirs = NULL;
1802   gchar **retval;
1803   gchar *p;
1804   gchar *exe_root;
1805       
1806   if (address_of_function)
1807     {
1808       G_LOCK (g_utils_global);
1809       hmodule = get_module_for_address (address_of_function);
1810       if (hmodule != NULL)
1811         {
1812           if (per_module_data_dirs == NULL)
1813             per_module_data_dirs = g_hash_table_new (NULL, NULL);
1814           else
1815             {
1816               retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1817               
1818               if (retval != NULL)
1819                 {
1820                   G_UNLOCK (g_utils_global);
1821                   return (const gchar * const *) retval;
1822                 }
1823             }
1824         }
1825     }
1826
1827   data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1828
1829   /* Documents and Settings\All Users\Application Data */
1830   p = get_special_folder (CSIDL_COMMON_APPDATA);
1831   if (p)
1832     g_array_append_val (data_dirs, p);
1833   
1834   /* Documents and Settings\All Users\Documents */
1835   p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1836   if (p)
1837     g_array_append_val (data_dirs, p);
1838         
1839   /* Using the above subfolders of Documents and Settings perhaps
1840    * makes sense from a Windows perspective.
1841    *
1842    * But looking at the actual use cases of this function in GTK+
1843    * and GNOME software, what we really want is the "share"
1844    * subdirectory of the installation directory for the package
1845    * our caller is a part of.
1846    *
1847    * The address_of_function parameter, if non-NULL, points to a
1848    * function in the calling module. Use that to determine that
1849    * module's installation folder, and use its "share" subfolder.
1850    *
1851    * Additionally, also use the "share" subfolder of the installation
1852    * locations of GLib and the .exe file being run.
1853    *
1854    * To guard against none of the above being what is really wanted,
1855    * callers of this function should have Win32-specific code to look
1856    * up their installation folder themselves, and handle a subfolder
1857    * "share" of it in the same way as the folders returned from this
1858    * function.
1859    */
1860
1861   p = get_module_share_dir (address_of_function);
1862   if (p)
1863     g_array_append_val (data_dirs, p);
1864     
1865   if (glib_dll != NULL)
1866     {
1867       gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1868       p = g_build_filename (glib_root, "share", NULL);
1869       if (p)
1870         g_array_append_val (data_dirs, p);
1871       g_free (glib_root);
1872     }
1873   
1874   exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1875   p = g_build_filename (exe_root, "share", NULL);
1876   if (p)
1877     g_array_append_val (data_dirs, p);
1878   g_free (exe_root);
1879
1880   retval = (gchar **) g_array_free (data_dirs, FALSE);
1881
1882   if (address_of_function)
1883     {
1884       if (hmodule != NULL)
1885         g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1886       G_UNLOCK (g_utils_global);
1887     }
1888
1889   return (const gchar * const *) retval;
1890 }
1891
1892 #endif
1893
1894 /**
1895  * g_get_system_data_dirs:
1896  * 
1897  * Returns an ordered list of base directories in which to access 
1898  * system-wide application data.
1899  *
1900  * On UNIX platforms this is determined using the mechanisms described in
1901  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1902  * XDG Base Directory Specification</ulink>
1903  * In this case the list of directories retrieved will be XDG_DATA_DIRS.
1904  *
1905  * On Windows the first elements in the list are the Application Data
1906  * and Documents folders for All Users. (These can be determined only
1907  * on Windows 2000 or later and are not present in the list on other
1908  * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1909  * CSIDL_COMMON_DOCUMENTS.
1910  *
1911  * Then follows the "share" subfolder in the installation folder for
1912  * the package containing the DLL that calls this function, if it can
1913  * be determined.
1914  * 
1915  * Finally the list contains the "share" subfolder in the installation
1916  * folder for GLib, and in the installation folder for the package the
1917  * application's .exe file belongs to.
1918  *
1919  * The installation folders above are determined by looking up the
1920  * folder where the module (DLL or EXE) in question is located. If the
1921  * folder's name is "bin", its parent is used, otherwise the folder
1922  * itself.
1923  *
1924  * Note that on Windows the returned list can vary depending on where
1925  * this function is called.
1926  *
1927  * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must 
1928  *               not be modified or freed.
1929  * Since: 2.6
1930  **/
1931 const gchar * const * 
1932 g_get_system_data_dirs (void)
1933 {
1934   gchar **data_dir_vector;
1935
1936   G_LOCK (g_utils_global);
1937
1938   if (!g_system_data_dirs)
1939     {
1940 #ifdef G_OS_WIN32
1941       data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
1942 #else
1943       gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1944
1945       if (!data_dirs || !data_dirs[0])
1946           data_dirs = "/usr/local/share/:/usr/share/";
1947
1948       data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1949 #endif
1950
1951       g_system_data_dirs = data_dir_vector;
1952     }
1953   else
1954     data_dir_vector = g_system_data_dirs;
1955
1956   G_UNLOCK (g_utils_global);
1957
1958   return (const gchar * const *) data_dir_vector;
1959 }
1960
1961 /**
1962  * g_get_system_config_dirs:
1963  * 
1964  * Returns an ordered list of base directories in which to access 
1965  * system-wide configuration information.
1966  *
1967  * On UNIX platforms this is determined using the mechanisms described in
1968  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1969  * XDG Base Directory Specification</ulink>.
1970  * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
1971  *
1972  * On Windows is the directory that contains application data for all users.
1973  * A typical path is C:\Documents and Settings\All Users\Application Data.
1974  * This folder is used for application data that is not user specific.
1975  * For example, an application can store a spell-check dictionary, a database
1976  * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
1977  * This information will not roam and is available to anyone using the computer.
1978  *
1979  * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must 
1980  *               not be modified or freed.
1981  * Since: 2.6
1982  **/
1983 const gchar * const *
1984 g_get_system_config_dirs (void)
1985 {
1986   gchar *conf_dirs, **conf_dir_vector;
1987
1988   G_LOCK (g_utils_global);
1989
1990   if (!g_system_config_dirs)
1991     {
1992 #ifdef G_OS_WIN32
1993       conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
1994       if (conf_dirs)
1995         {
1996           conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1997           g_free (conf_dirs);
1998         }
1999       else
2000         {
2001           /* Return empty list */
2002           conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2003         }
2004 #else
2005       conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2006
2007       if (!conf_dirs || !conf_dirs[0])
2008           conf_dirs = "/etc/xdg";
2009
2010       conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2011 #endif
2012
2013       g_system_config_dirs = conf_dir_vector;
2014     }
2015   else
2016     conf_dir_vector = g_system_config_dirs;
2017   G_UNLOCK (g_utils_global);
2018
2019   return (const gchar * const *) conf_dir_vector;
2020 }
2021
2022 /**
2023  * g_nullify_pointer:
2024  * @nullify_location: the memory address of the pointer.
2025  *
2026  * Set the pointer at the specified location to %NULL.
2027  **/
2028 void
2029 g_nullify_pointer (gpointer *nullify_location)
2030 {
2031   g_return_if_fail (nullify_location != NULL);
2032
2033   *nullify_location = NULL;
2034 }
2035
2036 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2037 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2038 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2039 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2040 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2041 #define EXABYTE_FACTOR  (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2042
2043 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2044 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2045 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2046 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2047 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2048 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2049
2050 /**
2051  * g_format_size:
2052  * @size: a size in bytes
2053  *
2054  * Formats a size (for example the size of a file) into a human readable
2055  * string.  Sizes are rounded to the nearest size prefix (kB, MB, GB)
2056  * and are displayed rounded to the nearest tenth. E.g. the file size
2057  * 3292528 bytes will be converted into the string "3.2 MB".
2058  *
2059  * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2060  *
2061  * This string should be freed with g_free() when not needed any longer.
2062  *
2063  * See g_format_size_full() for more options about how the size might be
2064  * formatted.
2065  *
2066  * Returns: a newly-allocated formatted string containing a human readable
2067  *     file size
2068  *
2069  * Since: 2.30
2070  */
2071 gchar *
2072 g_format_size (guint64 size)
2073 {
2074   return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2075 }
2076
2077 /**
2078  * GFormatSizeFlags:
2079  * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2080  * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2081  *     of the returned string.  For example, "45.6 kB (45,612 bytes)".
2082  * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2083  *     suffixes. IEC units should only be used for reporting things with
2084  *     a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2085  *     Network and storage sizes should be reported in the normal SI units.
2086  *
2087  * Flags to modify the format of the string returned by g_format_size_full().
2088  */
2089
2090 #pragma GCC diagnostic push
2091 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2092
2093 /**
2094  * g_format_size_full:
2095  * @size: a size in bytes
2096  * @flags: #GFormatSizeFlags to modify the output
2097  *
2098  * Formats a size.
2099  *
2100  * This function is similar to g_format_size() but allows for flags
2101  * that modify the output. See #GFormatSizeFlags.
2102  *
2103  * Returns: a newly-allocated formatted string containing a human
2104  *     readable file size
2105  *
2106  * Since: 2.30
2107  */
2108 gchar *
2109 g_format_size_full (guint64          size,
2110                     GFormatSizeFlags flags)
2111 {
2112   GString *string;
2113
2114   string = g_string_new (NULL);
2115
2116   if (flags & G_FORMAT_SIZE_IEC_UNITS)
2117     {
2118       if (size < KIBIBYTE_FACTOR)
2119         {
2120           g_string_printf (string,
2121                            g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2122                            (guint) size);
2123           flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2124         }
2125
2126       else if (size < MEBIBYTE_FACTOR)
2127         g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2128       else if (size < GIBIBYTE_FACTOR)
2129         g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2130
2131       else if (size < TEBIBYTE_FACTOR)
2132         g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2133
2134       else if (size < PEBIBYTE_FACTOR)
2135         g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2136
2137       else if (size < EXBIBYTE_FACTOR)
2138         g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2139
2140       else
2141         g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2142     }
2143   else
2144     {
2145       if (size < KILOBYTE_FACTOR)
2146         {
2147           g_string_printf (string,
2148                            g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2149                            (guint) size);
2150           flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2151         }
2152
2153       else if (size < MEGABYTE_FACTOR)
2154         g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2155
2156       else if (size < GIGABYTE_FACTOR)
2157         g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2158
2159       else if (size < TERABYTE_FACTOR)
2160         g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2161       else if (size < PETABYTE_FACTOR)
2162         g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2163
2164       else if (size < EXABYTE_FACTOR)
2165         g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2166
2167       else
2168         g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2169     }
2170
2171   if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2172     {
2173       /* First problem: we need to use the number of bytes to decide on
2174        * the plural form that is used for display, but the number of
2175        * bytes potentially exceeds the size of a guint (which is what
2176        * ngettext() takes).
2177        *
2178        * From a pragmatic standpoint, it seems that all known languages
2179        * base plural forms on one or both of the following:
2180        *
2181        *   - the lowest digits of the number
2182        *
2183        *   - if the number if greater than some small value
2184        *
2185        * Here's how we fake it:  Draw an arbitrary line at one thousand.
2186        * If the number is below that, then fine.  If it is above it,
2187        * then we take the modulus of the number by one thousand (in
2188        * order to keep the lowest digits) and add one thousand to that
2189        * (in order to ensure that 1001 is not treated the same as 1).
2190        */
2191       guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2192
2193       /* Second problem: we need to translate the string "%u byte" and
2194        * "%u bytes" for pluralisation, but the correct number format to
2195        * use for a gsize is different depending on which architecture
2196        * we're on.
2197        *
2198        * Solution: format the number separately and use "%s bytes" on
2199        * all platforms.
2200        */
2201       const gchar *translated_format;
2202       gchar *formatted_number;
2203
2204       /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2205       translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2206       /* XXX: Windows doesn't support the "'" format modifier, so we
2207        * must not use it there.  Instead, just display the number
2208        * without separation.  Bug #655336 is open until a solution is
2209        * found.
2210        */
2211 #ifndef G_OS_WIN32
2212       formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2213 #else
2214       formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2215 #endif
2216
2217       g_string_append (string, " (");
2218       g_string_append_printf (string, translated_format, formatted_number);
2219       g_free (formatted_number);
2220       g_string_append (string, ")");
2221     }
2222
2223   return g_string_free (string, FALSE);
2224 }
2225
2226 #pragma GCC diagnostic pop
2227
2228 /**
2229  * g_format_size_for_display:
2230  * @size: a size in bytes
2231  *
2232  * Formats a size (for example the size of a file) into a human
2233  * readable string. Sizes are rounded to the nearest size prefix
2234  * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2235  * E.g. the file size 3292528 bytes will be converted into the
2236  * string "3.1 MB".
2237  *
2238  * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2239  *
2240  * This string should be freed with g_free() when not needed any longer.
2241  *
2242  * Returns: a newly-allocated formatted string containing a human
2243  *     readable file size
2244  *
2245  * Since: 2.16
2246  *
2247  * Deprecated:2.30: This function is broken due to its use of SI
2248  *     suffixes to denote IEC units. Use g_format_size() instead.
2249  */
2250 gchar *
2251 g_format_size_for_display (goffset size)
2252 {
2253   if (size < (goffset) KIBIBYTE_FACTOR)
2254     return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2255   else
2256     {
2257       gdouble displayed_size;
2258
2259       if (size < (goffset) MEBIBYTE_FACTOR)
2260         {
2261           displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2262           /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2263            * mean 1024 bytes.  I am aware that 'KB' is not correct, but it has been preserved for reasons of
2264            * compatibility.  Users will not see this string unless a program is using this deprecated function.
2265            * Please translate as literally as possible.
2266            */
2267           return g_strdup_printf (_("%.1f KB"), displayed_size);
2268         }
2269       else if (size < (goffset) GIBIBYTE_FACTOR)
2270         {
2271           displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2272           return g_strdup_printf (_("%.1f MB"), displayed_size);
2273         }
2274       else if (size < (goffset) TEBIBYTE_FACTOR)
2275         {
2276           displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2277           return g_strdup_printf (_("%.1f GB"), displayed_size);
2278         }
2279       else if (size < (goffset) PEBIBYTE_FACTOR)
2280         {
2281           displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2282           return g_strdup_printf (_("%.1f TB"), displayed_size);
2283         }
2284       else if (size < (goffset) EXBIBYTE_FACTOR)
2285         {
2286           displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2287           return g_strdup_printf (_("%.1f PB"), displayed_size);
2288         }
2289       else
2290         {
2291           displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2292           return g_strdup_printf (_("%.1f EB"), displayed_size);
2293         }
2294     }
2295 }
2296
2297 #if defined (G_OS_WIN32) && !defined (_WIN64)
2298
2299 /* Binary compatibility versions. Not for newly compiled code. */
2300
2301 _GLIB_EXTERN const gchar *g_get_user_name_utf8        (void);
2302 _GLIB_EXTERN const gchar *g_get_real_name_utf8        (void);
2303 _GLIB_EXTERN const gchar *g_get_home_dir_utf8         (void);
2304 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8          (void);
2305 _GLIB_EXTERN gchar       *g_find_program_in_path_utf8 (const gchar *program);
2306
2307 gchar *
2308 g_find_program_in_path_utf8 (const gchar *program)
2309 {
2310   return g_find_program_in_path (program);
2311 }
2312
2313 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2314 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2315 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2316 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2317
2318 #endif
2319
2320 /* Private API:
2321  *
2322  * Returns %TRUE if the current process was executed as setuid (or an
2323  * equivalent __libc_enable_secure is available).  See:
2324  * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
2325  */ 
2326 gboolean
2327 g_check_setuid (void)
2328 {
2329   /* TODO: get __libc_enable_secure exported from glibc.
2330    * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
2331    */
2332 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
2333   {
2334     /* See glibc/include/unistd.h */
2335     extern int __libc_enable_secure;
2336     return __libc_enable_secure;
2337   }
2338 #elif defined(HAVE_ISSETUGID)
2339   /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2340   return issetugid ();
2341 #elif defined(G_OS_UNIX)
2342   uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2343   gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2344
2345   static gsize check_setuid_initialised;
2346   static gboolean is_setuid;
2347
2348   if (g_once_init_enter (&check_setuid_initialised))
2349     {
2350 #ifdef HAVE_GETRESUID
2351       /* These aren't in the header files, so we prototype them here.
2352        */
2353       int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2354       int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2355       
2356       if (getresuid (&ruid, &euid, &suid) != 0 ||
2357           getresgid (&rgid, &egid, &sgid) != 0)
2358 #endif /* HAVE_GETRESUID */
2359         {
2360           suid = ruid = getuid ();
2361           sgid = rgid = getgid ();
2362           euid = geteuid ();
2363           egid = getegid ();
2364         }
2365
2366       is_setuid = (ruid != euid || ruid != suid ||
2367                    rgid != egid || rgid != sgid);
2368
2369       g_once_init_leave (&check_setuid_initialised, 1);
2370     }
2371   return is_setuid;
2372 #else
2373   return FALSE;
2374 #endif
2375 }