docs: Small improvements to glib-mkenums man page
[glib.git] / glib / genviron.c
blob9c8151c20672d76fe4d64367cb528deeac788503
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1998 Peter Mattis, Spencer Kimball and Josh MacDonald
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.1 of the License, or (at your option) any later version.
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.
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/>.
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/.
25 #include "config.h"
27 #include "genviron.h"
29 #include <stdlib.h>
30 #include <string.h>
31 #ifdef HAVE_CRT_EXTERNS_H
32 #include <crt_externs.h> /* for _NSGetEnviron */
33 #endif
34 #ifdef G_OS_WIN32
35 #include <windows.h>
36 #endif
38 #include "glib-private.h"
39 #include "gmem.h"
40 #include "gmessages.h"
41 #include "gstrfuncs.h"
42 #include "gunicode.h"
43 #include "gconvert.h"
44 #include "gquark.h"
46 /* Environ array functions {{{1 */
47 static gint
48 g_environ_find (gchar **envp,
49 const gchar *variable)
51 gint len, i;
53 if (envp == NULL)
54 return -1;
56 len = strlen (variable);
58 for (i = 0; envp[i]; i++)
60 if (strncmp (envp[i], variable, len) == 0 &&
61 envp[i][len] == '=')
62 return i;
65 return -1;
68 /**
69 * g_environ_getenv:
70 * @envp: (nullable) (array zero-terminated=1) (transfer none) (element-type filename):
71 * an environment list (eg, as returned from g_get_environ()), or %NULL
72 * for an empty environment list
73 * @variable: (type filename): the environment variable to get
75 * Returns the value of the environment variable @variable in the
76 * provided list @envp.
78 * Returns: (type filename): the value of the environment variable, or %NULL if
79 * the environment variable is not set in @envp. The returned
80 * string is owned by @envp, and will be freed if @variable is
81 * set or unset again.
83 * Since: 2.32
85 const gchar *
86 g_environ_getenv (gchar **envp,
87 const gchar *variable)
89 gint index;
91 g_return_val_if_fail (variable != NULL, NULL);
93 index = g_environ_find (envp, variable);
94 if (index != -1)
95 return envp[index] + strlen (variable) + 1;
96 else
97 return NULL;
101 * g_environ_setenv:
102 * @envp: (nullable) (array zero-terminated=1) (element-type filename) (transfer full):
103 * an environment list that can be freed using g_strfreev() (e.g., as
104 * returned from g_get_environ()), or %NULL for an empty
105 * environment list
106 * @variable: (type filename): the environment variable to set, must not
107 * contain '='
108 * @value: (type filename): the value for to set the variable to
109 * @overwrite: whether to change the variable if it already exists
111 * Sets the environment variable @variable in the provided list
112 * @envp to @value.
114 * Returns: (array zero-terminated=1) (element-type filename) (transfer full):
115 * the updated environment list. Free it using g_strfreev().
117 * Since: 2.32
119 gchar **
120 g_environ_setenv (gchar **envp,
121 const gchar *variable,
122 const gchar *value,
123 gboolean overwrite)
125 gint index;
127 g_return_val_if_fail (variable != NULL, NULL);
128 g_return_val_if_fail (strchr (variable, '=') == NULL, NULL);
129 g_return_val_if_fail (value != NULL, NULL);
131 index = g_environ_find (envp, variable);
132 if (index != -1)
134 if (overwrite)
136 g_free (envp[index]);
137 envp[index] = g_strdup_printf ("%s=%s", variable, value);
140 else
142 gint length;
144 length = envp ? g_strv_length (envp) : 0;
145 envp = g_renew (gchar *, envp, length + 2);
146 envp[length] = g_strdup_printf ("%s=%s", variable, value);
147 envp[length + 1] = NULL;
150 return envp;
153 static gchar **
154 g_environ_unsetenv_internal (gchar **envp,
155 const gchar *variable,
156 gboolean free_value)
158 gint len;
159 gchar **e, **f;
161 len = strlen (variable);
163 /* Note that we remove *all* environment entries for
164 * the variable name, not just the first.
166 e = f = envp;
167 while (*e != NULL)
169 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
171 *f = *e;
172 f++;
174 else
176 if (free_value)
177 g_free (*e);
180 e++;
182 *f = NULL;
184 return envp;
189 * g_environ_unsetenv:
190 * @envp: (nullable) (array zero-terminated=1) (element-type filename) (transfer full):
191 * an environment list that can be freed using g_strfreev() (e.g., as
192 * returned from g_get_environ()), or %NULL for an empty environment list
193 * @variable: (type filename): the environment variable to remove, must not
194 * contain '='
196 * Removes the environment variable @variable from the provided
197 * environment @envp.
199 * Returns: (array zero-terminated=1) (element-type filename) (transfer full):
200 * the updated environment list. Free it using g_strfreev().
202 * Since: 2.32
204 gchar **
205 g_environ_unsetenv (gchar **envp,
206 const gchar *variable)
208 g_return_val_if_fail (variable != NULL, NULL);
209 g_return_val_if_fail (strchr (variable, '=') == NULL, NULL);
211 if (envp == NULL)
212 return NULL;
214 return g_environ_unsetenv_internal (envp, variable, TRUE);
217 /* UNIX implemention {{{1 */
218 #ifndef G_OS_WIN32
221 * g_getenv:
222 * @variable: (type filename): the environment variable to get
224 * Returns the value of an environment variable.
226 * On UNIX, the name and value are byte strings which might or might not
227 * be in some consistent character set and encoding. On Windows, they are
228 * in UTF-8.
229 * On Windows, in case the environment variable's value contains
230 * references to other environment variables, they are expanded.
232 * Returns: (type filename): the value of the environment variable, or %NULL if
233 * the environment variable is not found. The returned string
234 * may be overwritten by the next call to g_getenv(), g_setenv()
235 * or g_unsetenv().
237 const gchar *
238 g_getenv (const gchar *variable)
240 g_return_val_if_fail (variable != NULL, NULL);
242 return getenv (variable);
246 * g_setenv:
247 * @variable: (type filename): the environment variable to set, must not
248 * contain '='.
249 * @value: (type filename): the value for to set the variable to.
250 * @overwrite: whether to change the variable if it already exists.
252 * Sets an environment variable. On UNIX, both the variable's name and
253 * value can be arbitrary byte strings, except that the variable's name
254 * cannot contain '='. On Windows, they should be in UTF-8.
256 * Note that on some systems, when variables are overwritten, the memory
257 * used for the previous variables and its value isn't reclaimed.
259 * You should be mindful of the fact that environment variable handling
260 * in UNIX is not thread-safe, and your program may crash if one thread
261 * calls g_setenv() while another thread is calling getenv(). (And note
262 * that many functions, such as gettext(), call getenv() internally.)
263 * This function is only safe to use at the very start of your program,
264 * before creating any other threads (or creating objects that create
265 * worker threads of their own).
267 * If you need to set up the environment for a child process, you can
268 * use g_get_environ() to get an environment array, modify that with
269 * g_environ_setenv() and g_environ_unsetenv(), and then pass that
270 * array directly to execvpe(), g_spawn_async(), or the like.
272 * Returns: %FALSE if the environment variable couldn't be set.
274 * Since: 2.4
276 gboolean
277 g_setenv (const gchar *variable,
278 const gchar *value,
279 gboolean overwrite)
281 gint result;
282 #ifndef HAVE_SETENV
283 gchar *string;
284 #endif
286 g_return_val_if_fail (variable != NULL, FALSE);
287 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
288 g_return_val_if_fail (value != NULL, FALSE);
290 #ifdef HAVE_SETENV
291 result = setenv (variable, value, overwrite);
292 #else
293 if (!overwrite && getenv (variable) != NULL)
294 return TRUE;
296 /* This results in a leak when you overwrite existing
297 * settings. It would be fairly easy to fix this by keeping
298 * our own parallel array or hash table.
300 string = g_strconcat (variable, "=", value, NULL);
301 result = putenv (string);
302 #endif
303 return result == 0;
306 #ifdef HAVE__NSGETENVIRON
307 #define environ (*_NSGetEnviron())
308 #else
309 /* According to the Single Unix Specification, environ is not
310 * in any system header, although unistd.h often declares it.
312 extern char **environ;
313 #endif
316 * g_unsetenv:
317 * @variable: (type filename): the environment variable to remove, must
318 * not contain '='
320 * Removes an environment variable from the environment.
322 * Note that on some systems, when variables are overwritten, the
323 * memory used for the previous variables and its value isn't reclaimed.
325 * You should be mindful of the fact that environment variable handling
326 * in UNIX is not thread-safe, and your program may crash if one thread
327 * calls g_unsetenv() while another thread is calling getenv(). (And note
328 * that many functions, such as gettext(), call getenv() internally.) This
329 * function is only safe to use at the very start of your program, before
330 * creating any other threads (or creating objects that create worker
331 * threads of their own).
333 * If you need to set up the environment for a child process, you can
334 * use g_get_environ() to get an environment array, modify that with
335 * g_environ_setenv() and g_environ_unsetenv(), and then pass that
336 * array directly to execvpe(), g_spawn_async(), or the like.
338 * Since: 2.4
340 void
341 g_unsetenv (const gchar *variable)
343 g_return_if_fail (variable != NULL);
344 g_return_if_fail (strchr (variable, '=') == NULL);
346 #ifdef HAVE_UNSETENV
347 unsetenv (variable);
348 #else /* !HAVE_UNSETENV */
349 /* Mess directly with the environ array.
350 * This seems to be the only portable way to do this.
352 g_environ_unsetenv_internal (environ, variable, FALSE);
353 #endif /* !HAVE_UNSETENV */
357 * g_listenv:
359 * Gets the names of all variables set in the environment.
361 * Programs that want to be portable to Windows should typically use
362 * this function and g_getenv() instead of using the environ array
363 * from the C library directly. On Windows, the strings in the environ
364 * array are in system codepage encoding, while in most of the typical
365 * use cases for environment variables in GLib-using programs you want
366 * the UTF-8 encoding that this function and g_getenv() provide.
368 * Returns: (array zero-terminated=1) (element-type filename) (transfer full):
369 * a %NULL-terminated list of strings which must be freed with
370 * g_strfreev().
372 * Since: 2.8
374 gchar **
375 g_listenv (void)
377 gchar **result, *eq;
378 gint len, i, j;
380 len = g_strv_length (environ);
381 result = g_new0 (gchar *, len + 1);
383 j = 0;
384 for (i = 0; i < len; i++)
386 eq = strchr (environ[i], '=');
387 if (eq)
388 result[j++] = g_strndup (environ[i], eq - environ[i]);
391 result[j] = NULL;
393 return result;
397 * g_get_environ:
399 * Gets the list of environment variables for the current process.
401 * The list is %NULL terminated and each item in the list is of the
402 * form 'NAME=VALUE'.
404 * This is equivalent to direct access to the 'environ' global variable,
405 * except portable.
407 * The return value is freshly allocated and it should be freed with
408 * g_strfreev() when it is no longer needed.
410 * Returns: (array zero-terminated=1) (element-type filename) (transfer full):
411 * the list of environment variables
413 * Since: 2.28
415 gchar **
416 g_get_environ (void)
418 return g_strdupv (environ);
421 /* Win32 implementation {{{1 */
422 #else /* G_OS_WIN32 */
424 const gchar *
425 g_getenv (const gchar *variable)
427 GQuark quark;
428 gchar *value;
429 wchar_t dummy[2], *wname, *wvalue;
430 int len;
432 g_return_val_if_fail (variable != NULL, NULL);
433 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
435 /* On Windows NT, it is relatively typical that environment
436 * variables contain references to other environment variables. If
437 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
438 * environment variables would be stored in the Registry as
439 * REG_EXPAND_SZ type values, and would then get automatically
440 * expanded before a program sees them. But there is broken software
441 * that stores environment variables as REG_SZ values even if they
442 * contain references to other environment variables.)
445 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
447 len = GetEnvironmentVariableW (wname, dummy, 2);
449 if (len == 0)
451 g_free (wname);
452 if (GetLastError () == ERROR_ENVVAR_NOT_FOUND)
453 return NULL;
455 quark = g_quark_from_static_string ("");
456 return g_quark_to_string (quark);
458 else if (len == 1)
459 len = 2;
461 wvalue = g_new (wchar_t, len);
463 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
465 g_free (wname);
466 g_free (wvalue);
467 return NULL;
470 if (wcschr (wvalue, L'%') != NULL)
472 wchar_t *tem = wvalue;
474 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
476 if (len > 0)
478 wvalue = g_new (wchar_t, len);
480 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
482 g_free (wvalue);
483 wvalue = tem;
485 else
486 g_free (tem);
490 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
492 g_free (wname);
493 g_free (wvalue);
495 quark = g_quark_from_string (value);
496 g_free (value);
498 return g_quark_to_string (quark);
501 gboolean
502 g_setenv (const gchar *variable,
503 const gchar *value,
504 gboolean overwrite)
506 gboolean retval;
507 wchar_t *wname, *wvalue, *wassignment;
508 gchar *tem;
510 g_return_val_if_fail (variable != NULL, FALSE);
511 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
512 g_return_val_if_fail (value != NULL, FALSE);
513 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
514 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
516 if (!overwrite && g_getenv (variable) != NULL)
517 return TRUE;
519 /* We want to (if possible) set both the environment variable copy
520 * kept by the C runtime and the one kept by the system.
522 * We can't use only the C runtime's putenv or _wputenv() as that
523 * won't work for arbitrary Unicode strings in a "non-Unicode" app
524 * (with main() and not wmain()). In a "main()" app the C runtime
525 * initializes the C runtime's environment table by converting the
526 * real (wide char) environment variables to system codepage, thus
527 * breaking those that aren't representable in the system codepage.
529 * As the C runtime's putenv() will also set the system copy, we do
530 * the putenv() first, then call SetEnvironmentValueW ourselves.
533 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
534 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
535 tem = g_strconcat (variable, "=", value, NULL);
536 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
538 g_free (tem);
539 _wputenv (wassignment);
540 g_free (wassignment);
542 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
544 g_free (wname);
545 g_free (wvalue);
547 return retval;
550 void
551 g_unsetenv (const gchar *variable)
553 wchar_t *wname, *wassignment;
554 gchar *tem;
556 g_return_if_fail (variable != NULL);
557 g_return_if_fail (strchr (variable, '=') == NULL);
558 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
560 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
561 tem = g_strconcat (variable, "=", NULL);
562 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
564 g_free (tem);
565 _wputenv (wassignment);
566 g_free (wassignment);
568 SetEnvironmentVariableW (wname, NULL);
570 g_free (wname);
573 gchar **
574 g_listenv (void)
576 gchar **result, *eq;
577 gint len = 0, j;
578 wchar_t *p, *q;
580 p = (wchar_t *) GetEnvironmentStringsW ();
581 if (p != NULL)
583 q = p;
584 while (*q)
586 q += wcslen (q) + 1;
587 len++;
590 result = g_new0 (gchar *, len + 1);
592 j = 0;
593 q = p;
594 while (*q)
596 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
597 if (result[j] != NULL)
599 eq = strchr (result[j], '=');
600 if (eq && eq > result[j])
602 *eq = '\0';
603 j++;
605 else
606 g_free (result[j]);
608 q += wcslen (q) + 1;
610 result[j] = NULL;
611 FreeEnvironmentStringsW (p);
613 return result;
616 gchar **
617 g_get_environ (void)
619 gunichar2 *strings;
620 gchar **result;
621 gint i, n;
623 strings = GetEnvironmentStringsW ();
624 for (n = 0, i = 0; strings[n]; i++)
625 n += wcslen (strings + n) + 1;
627 result = g_new (char *, i + 1);
628 for (n = 0, i = 0; strings[n]; i++)
630 result[i] = g_utf16_to_utf8 (strings + n, -1, NULL, NULL, NULL);
631 n += wcslen (strings + n) + 1;
633 FreeEnvironmentStringsW (strings);
634 result[i] = NULL;
636 return result;
639 #endif /* G_OS_WIN32 */
641 #ifdef G_OS_WIN32
643 /* Binary compatibility versions. Not for newly compiled code. */
645 _GLIB_EXTERN const gchar *g_getenv_utf8 (const gchar *variable);
646 _GLIB_EXTERN gboolean g_setenv_utf8 (const gchar *variable,
647 const gchar *value,
648 gboolean overwrite);
649 _GLIB_EXTERN void g_unsetenv_utf8 (const gchar *variable);
651 const gchar *
652 g_getenv_utf8 (const gchar *variable)
654 return g_getenv (variable);
657 gboolean
658 g_setenv_utf8 (const gchar *variable,
659 const gchar *value,
660 gboolean overwrite)
662 return g_setenv (variable, value, overwrite);
665 void
666 g_unsetenv_utf8 (const gchar *variable)
668 g_unsetenv (variable);
671 #endif
673 /* Epilogue {{{1 */
674 /* vim: set foldmethod=marker: */