-
Notifications
You must be signed in to change notification settings - Fork 541
/
Copy pathgutils.c
3360 lines (2939 loc) · 102 KB
/
gutils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* GLIB - Library of useful routines for C programming
* Copyright (C) 1995-1998 Peter Mattis, Spencer Kimball and Josh MacDonald
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
/*
* Modified by the GLib Team and others 1997-2000. See the AUTHORS
* file for a list of people on the GLib Team. See the ChangeLog
* files for a list of changes. These files are distributed with
* GLib at ftp://ftp.gtk.org/pub/gtk/.
*/
/*
* MT safe for the unix part, FIXME: make the win32 part MT safe as well.
*/
#include "config.h"
#include "gutils.h"
#include "gutilsprivate.h"
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <locale.h>
#include <string.h>
#include <ctype.h> /* For tolower() */
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef G_OS_UNIX
#include <pwd.h>
#include <sys/utsname.h>
#include <unistd.h>
#endif
#include <sys/types.h>
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef HAVE_CRT_EXTERNS_H
#include <crt_externs.h> /* for _NSGetEnviron */
#endif
#ifdef HAVE_SYS_AUXV_H
#include <sys/auxv.h>
#endif
#include "glib-init.h"
#include "glib-private.h"
#include "genviron.h"
#include "gfileutils.h"
#include "ggettext.h"
#include "ghash.h"
#include "gthread.h"
#include "gtestutils.h"
#include "gunicode.h"
#include "gstrfuncs.h"
#include "garray.h"
#include "glibintl.h"
#include "gstdio.h"
#include "gquark.h"
#ifdef G_PLATFORM_WIN32
#include "gconvert.h"
#include "gwin32.h"
#endif
#ifdef G_PLATFORM_WIN32
# include <windows.h>
# ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
# define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
# define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
# endif
# include <lmcons.h> /* For UNLEN */
#endif /* G_PLATFORM_WIN32 */
#ifdef G_OS_WIN32
# include <direct.h>
# include <shlobj.h>
# include <process.h>
#endif
#ifdef HAVE_CODESET
#include <langinfo.h>
#endif
/**
* g_memmove:
* @dest: the destination address to copy the bytes to.
* @src: the source address to copy the bytes from.
* @len: the number of bytes to copy.
*
* Copies a block of memory @len bytes long, from @src to @dest.
* The source and destination areas may overlap.
*
* Deprecated:2.40: Just use memmove().
*/
#ifdef G_OS_WIN32
#undef g_atexit
#endif
/**
* g_atexit:
* @func: (scope async): the function to call on normal program termination.
*
* Specifies a function to be called at normal program termination.
*
* Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
* macro that maps to a call to the atexit() function in the C
* library. This means that in case the code that calls g_atexit(),
* i.e. atexit(), is in a DLL, the function will be called when the
* DLL is detached from the program. This typically makes more sense
* than that the function is called when the GLib DLL is detached,
* which happened earlier when g_atexit() was a function in the GLib
* DLL.
*
* The behaviour of atexit() in the context of dynamically loaded
* modules is not formally specified and varies wildly.
*
* On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
* loaded module which is unloaded before the program terminates might
* well cause a crash at program exit.
*
* Some POSIX systems implement atexit() like Windows, and have each
* dynamically loaded module maintain an own atexit chain that is
* called when the module is unloaded.
*
* On other POSIX systems, before a dynamically loaded module is
* unloaded, the registered atexit functions (if any) residing in that
* module are called, regardless where the code that registered them
* resided. This is presumably the most robust approach.
*
* As can be seen from the above, for portability it's best to avoid
* calling g_atexit() (or atexit()) except in the main executable of a
* program.
*
* Deprecated:2.32: It is best to avoid g_atexit().
*/
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
void
g_atexit (GVoidFunc func)
{
gint result;
int errsv;
result = atexit ((void (*)(void)) func);
errsv = errno;
if (result)
{
g_error ("Could not register atexit() function: %s",
g_strerror (errsv));
}
}
G_GNUC_END_IGNORE_DEPRECATIONS
/* Based on execvp() from GNU Libc.
* Some of this code is cut-and-pasted into gspawn.c
*/
static gchar*
my_strchrnul (const gchar *str,
gchar c)
{
gchar *p = (gchar*)str;
while (*p && (*p != c))
++p;
return p;
}
#ifdef G_OS_WIN32
static gchar *inner_find_program_in_path (const gchar *program);
gchar*
g_find_program_in_path (const gchar *program)
{
const gchar *last_dot = strrchr (program, '.');
if (last_dot == NULL ||
strchr (last_dot, '\\') != NULL ||
strchr (last_dot, '/') != NULL)
{
const size_t program_length = strlen (program);
gchar *pathext = g_build_path (";",
".exe;.cmd;.bat;.com",
g_getenv ("PATHEXT"),
NULL);
gchar *p;
gchar *decorated_program;
gchar *retval;
p = pathext;
do
{
gchar *q = my_strchrnul (p, ';');
decorated_program = g_malloc (program_length + (q-p) + 1);
memcpy (decorated_program, program, program_length);
memcpy (decorated_program+program_length, p, q-p);
decorated_program [program_length + (q-p)] = '\0';
retval = inner_find_program_in_path (decorated_program);
g_free (decorated_program);
if (retval != NULL)
{
g_free (pathext);
return retval;
}
p = q;
} while (*p++ != '\0');
g_free (pathext);
return NULL;
}
else
return inner_find_program_in_path (program);
}
#endif
/**
* g_find_program_in_path:
* @program: (type filename): a program name in the GLib file name encoding
*
* Locates the first executable named @program in the user's path, in the
* same way that execvp() would locate it. Returns an allocated string
* with the absolute path name, or %NULL if the program is not found in
* the path. If @program is already an absolute path, returns a copy of
* @program if @program exists and is executable, and %NULL otherwise.
*
* On Windows, if @program does not have a file type suffix, tries
* with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
* the `PATHEXT` environment variable.
*
* On Windows, it looks for the file in the same way as CreateProcess()
* would. This means first in the directory where the executing
* program was loaded from, then in the current directory, then in the
* Windows 32-bit system directory, then in the Windows directory, and
* finally in the directories in the `PATH` environment variable. If
* the program is found, the return value contains the full name
* including the type suffix.
*
* Returns: (type filename) (transfer full) (nullable): a newly-allocated
* string with the absolute path, or %NULL
**/
#ifdef G_OS_WIN32
static gchar *
inner_find_program_in_path (const gchar *program)
#else
gchar*
g_find_program_in_path (const gchar *program)
#endif
{
return g_find_program_for_path (program, NULL, NULL);
}
/**
* g_find_program_for_path:
* @program: (type filename): a program name in the GLib file name encoding
* @path: (type filename) (nullable): the current dir where to search program
* @working_dir: (type filename) (nullable): the working dir where to search
* program
*
* Locates the first executable named @program in @path, in the
* same way that execvp() would locate it. Returns an allocated string
* with the absolute path name (taking in account the @working_dir), or
* %NULL if the program is not found in @path. If @program is already an
* absolute path, returns a copy of @program if @program exists and is
* executable, and %NULL otherwise.
*
* On Windows, if @path is %NULL, it looks for the file in the same way as
* CreateProcess() would. This means first in the directory where the
* executing program was loaded from, then in the current directory, then in
* the Windows 32-bit system directory, then in the Windows directory, and
* finally in the directories in the `PATH` environment variable. If
* the program is found, the return value contains the full name
* including the type suffix.
*
* Returns: (type filename) (transfer full) (nullable): a newly-allocated
* string with the absolute path, or %NULL
* Since: 2.76
**/
char *
g_find_program_for_path (const char *program,
const char *path,
const char *working_dir)
{
const char *original_path = path;
const char *original_program = program;
char *program_path = NULL;
const gchar *p;
gchar *name, *freeme;
#ifdef G_OS_WIN32
const gchar *path_copy;
gchar *filename = NULL, *appdir = NULL;
gchar *sysdir = NULL, *windir = NULL;
int n;
wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
wwindir[MAXPATHLEN];
#endif
gsize len;
gsize pathlen;
g_return_val_if_fail (program != NULL, NULL);
/* Use the working dir as program path if provided */
if (working_dir && !g_path_is_absolute (program))
{
program_path = g_build_filename (working_dir, program, NULL);
program = program_path;
}
/* If it is an absolute path, or a relative path including subdirectories,
* don't look in PATH.
*/
if (g_path_is_absolute (program)
|| strchr (original_program, G_DIR_SEPARATOR) != NULL
#ifdef G_OS_WIN32
|| strchr (original_program, '/') != NULL
#endif
)
{
if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
!g_file_test (program, G_FILE_TEST_IS_DIR))
{
gchar *out = NULL;
if (g_path_is_absolute (program))
{
out = g_strdup (program);
}
else
{
char *cwd = g_get_current_dir ();
out = g_build_filename (cwd, program, NULL);
g_free (cwd);
}
g_free (program_path);
return g_steal_pointer (&out);
}
else
{
g_clear_pointer (&program_path, g_free);
if (g_path_is_absolute (original_program))
return NULL;
}
}
program = original_program;
if G_LIKELY (original_path == NULL)
path = g_getenv ("PATH");
else
path = original_path;
#if defined(G_OS_UNIX)
if (path == NULL)
{
/* There is no 'PATH' in the environment. The default
* search path in GNU libc is the current directory followed by
* the path 'confstr' returns for '_CS_PATH'.
*/
/* In GLib we put . last, for security, and don't use the
* unportable confstr(); UNIX98 does not actually specify
* what to search if PATH is unset. POSIX may, dunno.
*/
path = "/bin:/usr/bin:.";
}
#else
if G_LIKELY (original_path == NULL)
{
n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
if (n > 0 && n < MAXPATHLEN)
filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
if (n > 0 && n < MAXPATHLEN)
sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
if (n > 0 && n < MAXPATHLEN)
windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
if (filename)
{
appdir = g_path_get_dirname (filename);
g_free (filename);
}
path = g_strdup (path);
if (windir)
{
const gchar *tem = path;
path = g_strconcat (windir, ";", path, NULL);
g_free ((gchar *) tem);
g_free (windir);
}
if (sysdir)
{
const gchar *tem = path;
path = g_strconcat (sysdir, ";", path, NULL);
g_free ((gchar *) tem);
g_free (sysdir);
}
{
const gchar *tem = path;
path = g_strconcat (".;", path, NULL);
g_free ((gchar *) tem);
}
if (appdir)
{
const gchar *tem = path;
path = g_strconcat (appdir, ";", path, NULL);
g_free ((gchar *) tem);
g_free (appdir);
}
path_copy = path;
}
else
{
path_copy = g_strdup (path);
}
#endif
len = strlen (program) + 1;
pathlen = strlen (path);
freeme = name = g_malloc (pathlen + len + 1);
/* Copy the file name at the top, including '\0' */
memcpy (name + pathlen + 1, program, len);
name = name + pathlen;
/* And add the slash before the filename */
*name = G_DIR_SEPARATOR;
p = path;
do
{
char *startp;
char *startp_path = NULL;
path = p;
p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
if (p == path)
/* Two adjacent colons, or a colon at the beginning or the end
* of 'PATH' means to search the current directory.
*/
startp = name + 1;
else
startp = memcpy (name - (p - path), path, p - path);
/* Use the working dir as program path if provided */
if (working_dir && !g_path_is_absolute (startp))
{
startp_path = g_build_filename (working_dir, startp, NULL);
startp = startp_path;
}
if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
!g_file_test (startp, G_FILE_TEST_IS_DIR))
{
gchar *ret;
if (g_path_is_absolute (startp)) {
ret = g_strdup (startp);
} else {
gchar *cwd = NULL;
cwd = g_get_current_dir ();
ret = g_build_filename (cwd, startp, NULL);
g_free (cwd);
}
g_free (program_path);
g_free (startp_path);
g_free (freeme);
#ifdef G_OS_WIN32
g_free ((gchar *) path_copy);
#endif
return ret;
}
g_free (startp_path);
}
while (*p++ != '\0');
g_free (program_path);
g_free (freeme);
#ifdef G_OS_WIN32
g_free ((gchar *) path_copy);
#endif
return NULL;
}
/* The functions below are defined this way for compatibility reasons.
* See the note in gutils.h.
*/
/**
* g_bit_nth_lsf:
* @mask: a #gulong containing flags
* @nth_bit: the index of the bit to start the search from
*
* Find the position of the first bit set in @mask, searching
* from (but not including) @nth_bit upwards. Bits are numbered
* from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
* usually). To start searching from the 0th bit, set @nth_bit to -1.
*
* Returns: the index of the first bit set which is higher than @nth_bit, or -1
* if no higher bits are set
*/
gint
(g_bit_nth_lsf) (gulong mask,
gint nth_bit)
{
return g_bit_nth_lsf_impl (mask, nth_bit);
}
/**
* g_bit_nth_msf:
* @mask: a #gulong containing flags
* @nth_bit: the index of the bit to start the search from
*
* Find the position of the first bit set in @mask, searching
* from (but not including) @nth_bit downwards. Bits are numbered
* from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
* usually). To start searching from the last bit, set @nth_bit to
* -1 or GLIB_SIZEOF_LONG * 8.
*
* Returns: the index of the first bit set which is lower than @nth_bit, or -1
* if no lower bits are set
*/
gint
(g_bit_nth_msf) (gulong mask,
gint nth_bit)
{
return g_bit_nth_msf_impl (mask, nth_bit);
}
/**
* g_bit_storage:
* @number: a #guint
*
* Gets the number of bits used to hold @number,
* e.g. if @number is 4, 3 bits are needed.
*
* Returns: the number of bits used to hold @number
*/
guint
(g_bit_storage) (gulong number)
{
return g_bit_storage_impl (number);
}
G_LOCK_DEFINE_STATIC (g_utils_global);
typedef struct
{
gchar *user_name;
gchar *real_name;
gchar *home_dir;
} UserDatabaseEntry;
/* These must all be read/written with @g_utils_global held. */
static gchar *g_user_data_dir = NULL;
static gchar **g_system_data_dirs = NULL;
static gchar *g_user_cache_dir = NULL;
static gchar *g_user_config_dir = NULL;
static gchar *g_user_state_dir = NULL;
static gchar *g_user_runtime_dir = NULL;
static gchar **g_system_config_dirs = NULL;
static gchar **g_user_special_dirs = NULL;
static gchar *g_tmp_dir = NULL;
/* fifteen minutes of fame for everybody */
#define G_USER_DIRS_EXPIRE 15 * 60
#ifdef G_OS_WIN32
static gchar *
get_special_folder (REFKNOWNFOLDERID known_folder_guid_ptr)
{
wchar_t *wcp = NULL;
gchar *result = NULL;
HRESULT hr;
hr = SHGetKnownFolderPath (known_folder_guid_ptr, 0, NULL, &wcp);
if (SUCCEEDED (hr))
result = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
CoTaskMemFree (wcp);
return result;
}
static char *
get_windows_directory_root (void)
{
wchar_t wwindowsdir[MAX_PATH];
if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
{
/* Usually X:\Windows, but in terminal server environments
* might be an UNC path, AFAIK.
*/
char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
char *p;
if (windowsdir == NULL)
return g_strdup ("C:\\");
p = (char *) g_path_skip_root (windowsdir);
if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
p--;
*p = '\0';
return windowsdir;
}
else
return g_strdup ("C:\\");
}
#endif
/* HOLDS: g_utils_global_lock */
static UserDatabaseEntry *
g_get_user_database_entry (void)
{
static UserDatabaseEntry *entry;
if (g_once_init_enter_pointer (&entry))
{
static UserDatabaseEntry e;
#ifdef G_OS_UNIX
{
struct passwd *pw = NULL;
gpointer buffer = NULL;
gint error;
const char *logname;
# if defined (HAVE_GETPWUID_R)
struct passwd pwd;
# ifdef _SC_GETPW_R_SIZE_MAX
/* This returns the maximum length */
glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
if (bufsize < 0)
bufsize = 64;
# else /* _SC_GETPW_R_SIZE_MAX */
glong bufsize = 64;
# endif /* _SC_GETPW_R_SIZE_MAX */
logname = g_getenv ("LOGNAME");
do
{
g_free (buffer);
/* we allocate 6 extra bytes to work around a bug in
* Mac OS < 10.3. See #156446
*/
buffer = g_malloc (bufsize + 6);
errno = 0;
if (logname) {
error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
if (!pw || (pw->pw_uid != getuid ())) {
/* LOGNAME is lying, fall back to looking up the uid */
error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
}
} else {
error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
}
error = error < 0 ? errno : error;
if (!pw)
{
/* we bail out prematurely if the user id can't be found
* (should be pretty rare case actually), or if the buffer
* should be sufficiently big and lookups are still not
* successful.
*/
if (error == 0 || error == ENOENT)
{
g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
(gulong) getuid ());
break;
}
if (bufsize > 32 * 1024)
{
g_warning ("getpwuid_r(): failed due to: %s.",
g_strerror (error));
break;
}
bufsize *= 2;
}
}
while (!pw);
# endif /* HAVE_GETPWUID_R */
if (!pw)
{
pw = getpwuid (getuid ());
}
if (pw)
{
e.user_name = g_strdup (pw->pw_name);
#ifndef __BIONIC__
if (pw->pw_gecos && *pw->pw_gecos != '\0' && pw->pw_name)
{
gchar **gecos_fields;
gchar **name_parts;
gchar *uppercase_pw_name;
/* split the gecos field and substitute '&' */
gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
name_parts = g_strsplit (gecos_fields[0], "&", 0);
uppercase_pw_name = g_strdup (pw->pw_name);
uppercase_pw_name[0] = g_ascii_toupper (uppercase_pw_name[0]);
e.real_name = g_strjoinv (uppercase_pw_name, name_parts);
g_strfreev (gecos_fields);
g_strfreev (name_parts);
g_free (uppercase_pw_name);
}
#endif
if (!e.home_dir)
e.home_dir = g_strdup (pw->pw_dir);
}
g_free (buffer);
}
#endif /* G_OS_UNIX */
#ifdef G_OS_WIN32
{
guint len = UNLEN+1;
wchar_t buffer[UNLEN+1];
if (GetUserNameW (buffer, (LPDWORD) &len))
{
e.user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
e.real_name = g_strdup (e.user_name);
}
}
#endif /* G_OS_WIN32 */
if (!e.user_name)
e.user_name = g_strdup ("somebody");
if (!e.real_name)
e.real_name = g_strdup ("Unknown");
g_once_init_leave_pointer (&entry, &e);
}
return entry;
}
/**
* g_get_user_name:
*
* Gets the user name of the current user. The encoding of the returned
* string is system-defined. On UNIX, it might be the preferred file name
* encoding, or something else, and there is no guarantee that it is even
* consistent on a machine. On Windows, it is always UTF-8.
*
* Returns: (type filename) (transfer none): the user name of the current user.
*/
const gchar *
g_get_user_name (void)
{
UserDatabaseEntry *entry;
entry = g_get_user_database_entry ();
return entry->user_name;
}
/**
* g_get_real_name:
*
* Gets the real name of the user. This usually comes from the user's
* entry in the `passwd` file. The encoding of the returned string is
* system-defined. (On Windows, it is, however, always UTF-8.) If the
* real user name cannot be determined, the string "Unknown" is
* returned.
*
* Returns: (type filename) (transfer none): the user's real name.
*/
const gchar *
g_get_real_name (void)
{
UserDatabaseEntry *entry;
entry = g_get_user_database_entry ();
return entry->real_name;
}
/* Protected by @g_utils_global_lock. */
static gchar *g_home_dir = NULL; /* (owned) (nullable before initialised) */
static gchar *
g_build_home_dir (void)
{
gchar *home_dir;
/* We first check HOME and use it if it is set */
home_dir = g_strdup (g_getenv ("HOME"));
#ifdef G_OS_WIN32
/* Only believe HOME if it is an absolute path and exists.
*
* We only do this check on Windows for a couple of reasons.
* Historically, we only did it there because we used to ignore $HOME
* on UNIX. There are concerns about enabling it now on UNIX because
* of things like autofs. In short, if the user has a bogus value in
* $HOME then they get what they pay for...
*/
if (home_dir != NULL)
{
if (!(g_path_is_absolute (home_dir) &&
g_file_test (home_dir, G_FILE_TEST_IS_DIR)))
g_clear_pointer (&home_dir, g_free);
}
/* In case HOME is Unix-style (it happens), convert it to
* Windows style.
*/
if (home_dir != NULL)
{
gchar *p;
while ((p = strchr (home_dir, '/')) != NULL)
*p = '\\';
}
if (home_dir == NULL)
{
/* USERPROFILE is probably the closest equivalent to $HOME? */
if (g_getenv ("USERPROFILE") != NULL)
home_dir = g_strdup (g_getenv ("USERPROFILE"));
}
if (home_dir == NULL)
home_dir = get_special_folder (&FOLDERID_Profile);
if (home_dir == NULL)
home_dir = get_windows_directory_root ();
#endif /* G_OS_WIN32 */
if (home_dir == NULL)
{
/* If we didn't get it from any of those methods, we will have
* to read the user database entry.
*/
UserDatabaseEntry *entry = g_get_user_database_entry ();
home_dir = g_strdup (entry->home_dir);
}
/* If we have been denied access to /etc/passwd (for example, by an
* overly-zealous LSM), make up a junk value. The return value at this
* point is explicitly documented as ‘undefined’. */
if (home_dir == NULL)
{
g_warning ("Could not find home directory: $HOME is not set, and "
"user database could not be read.");
home_dir = g_strdup ("/");
}
return g_steal_pointer (&home_dir);
}
/**
* g_get_home_dir:
*
* Gets the current user's home directory.
*
* As with most UNIX tools, this function will return the value of the
* `HOME` environment variable if it is set to an existing absolute path
* name, falling back to the `passwd` file in the case that it is unset.
*
* If the path given in `HOME` is non-absolute, does not exist, or is
* not a directory, the result is undefined.
*
* Before version 2.36 this function would ignore the `HOME` environment
* variable, taking the value from the `passwd` database instead. This was
* changed to increase the compatibility of GLib with other programs (and
* the XDG basedir specification) and to increase testability of programs
* based on GLib (by making it easier to run them from test frameworks).
*
* If your program has a strong requirement for either the new or the
* old behaviour (and if you don't wish to increase your GLib
* dependency to ensure that the new behaviour is in effect) then you
* should either directly check the `HOME` environment variable yourself
* or unset it before calling any functions in GLib.
*
* Returns: (type filename) (transfer none): the current user's home directory
*/
const gchar *
g_get_home_dir (void)
{
const gchar *home_dir;
G_LOCK (g_utils_global);
if (g_home_dir == NULL)
g_home_dir = g_build_home_dir ();
home_dir = g_home_dir;
G_UNLOCK (g_utils_global);
return home_dir;
}
void
_g_unset_cached_tmp_dir (void)
{
G_LOCK (g_utils_global);
/* We have to leak the old value, as user code could be retaining pointers
* to it. */
g_ignore_leak (g_tmp_dir);
g_tmp_dir = NULL;
G_UNLOCK (g_utils_global);
}
/**
* g_get_tmp_dir:
*
* Gets the directory to use for temporary files.
*
* On UNIX, this is taken from the `TMPDIR` environment variable.
* If the variable is not set, `P_tmpdir` is
* used, as defined by the system C library. Failing that, a
* hard-coded default of "/tmp" is returned.
*
* On Windows, the `TEMP` environment variable is used, with the
* root directory of the Windows installation (eg: "C:\") used
* as a default.
*
* The encoding of the returned string is system-defined. On Windows,
* it is always UTF-8. The return value is never %NULL or the empty
* string.
*
* Returns: (type filename) (transfer none): the directory to use for temporary files.
*/
const gchar *
g_get_tmp_dir (void)
{
G_LOCK (g_utils_global);
if (g_tmp_dir == NULL)
{
gchar *tmp;
tmp = g_strdup (g_getenv ("G_TEST_TMPDIR"));
if (tmp == NULL || *tmp == '\0')
{
g_free (tmp);
tmp = g_strdup (g_getenv (
#ifdef G_OS_WIN32
"TEMP"
#else /* G_OS_WIN32 */
"TMPDIR"
#endif /* G_OS_WIN32 */
));
}
#ifdef G_OS_WIN32
if (tmp == NULL || *tmp == '\0')
{