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