regex: Add FIRSTLINE compile flag
[platform/upstream/glib.git] / glib / genviron.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1998  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 #include "config.h"
28
29 #include "genviron.h"
30
31 #include <stdlib.h>
32 #include <string.h>
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #ifdef HAVE_CRT_EXTERNS_H
37 #include <crt_externs.h> /* for _NSGetEnviron */
38 #endif
39 #ifdef G_OS_WIN32
40 #include <windows.h>
41 #endif
42
43 #include "gmem.h"
44 #include "gmessages.h"
45 #include "gstrfuncs.h"
46 #include "gunicode.h"
47 #include "gconvert.h"
48 #include "gquark.h"
49
50 /* Environ array functions {{{1 */
51 static gint
52 g_environ_find (gchar       **envp,
53                 const gchar  *variable)
54 {
55   gint len, i;
56
57   if (envp == NULL)
58     return -1;
59
60   len = strlen (variable);
61
62   for (i = 0; envp[i]; i++)
63     {
64       if (strncmp (envp[i], variable, len) == 0 &&
65           envp[i][len] == '=')
66         return i;
67     }
68
69   return -1;
70 }
71
72 /**
73  * g_environ_getenv:
74  * @envp: (allow-none) (array zero-terminated=1) (transfer none): an environment
75  *     list (eg, as returned from g_get_environ()), or %NULL
76  *     for an empty environment list
77  * @variable: the environment variable to get, in the GLib file name
78  *     encoding
79  *
80  * Returns the value of the environment variable @variable in the
81  * provided list @envp.
82  *
83  * The name and value are in the GLib file name encoding.
84  * On UNIX, this means the actual bytes which might or might not
85  * be in some consistent character set and encoding. On Windows,
86  * it is in UTF-8. On Windows, in case the environment variable's
87  * value contains references to other environment variables, they
88  * are expanded.
89  *
90  * Return value: the value of the environment variable, or %NULL if
91  *     the environment variable is not set in @envp. The returned
92  *     string is owned by @envp, and will be freed if @variable is
93  *     set or unset again.
94  *
95  * Since: 2.32
96  */
97 const gchar *
98 g_environ_getenv (gchar       **envp,
99                   const gchar  *variable)
100 {
101   gint index;
102
103   g_return_val_if_fail (variable != NULL, NULL);
104
105   index = g_environ_find (envp, variable);
106   if (index != -1)
107     return envp[index] + strlen (variable) + 1;
108   else
109     return NULL;
110 }
111
112 /**
113  * g_environ_setenv:
114  * @envp: (allow-none) (array zero-terminated=1) (transfer full): an environment
115  *     list that can be freed using g_strfreev() (e.g., as returned from g_get_environ()), or %NULL
116  *     for an empty environment list
117  * @variable: the environment variable to set, must not contain '='
118  * @value: the value for to set the variable to
119  * @overwrite: whether to change the variable if it already exists
120  *
121  * Sets the environment variable @variable in the provided list
122  * @envp to @value.
123  *
124  * Both the variable's name and value should be in the GLib
125  * file name encoding. On UNIX, this means that they can be
126  * arbitrary byte strings. On Windows, they should be in UTF-8.
127  *
128  * Return value: (array zero-terminated=1) (transfer full): the
129  *     updated environment list. Free it using g_strfreev().
130  *
131  * Since: 2.32
132  */
133 gchar **
134 g_environ_setenv (gchar       **envp,
135                   const gchar  *variable,
136                   const gchar  *value,
137                   gboolean      overwrite)
138 {
139   gint index;
140
141   g_return_val_if_fail (variable != NULL, NULL);
142   g_return_val_if_fail (strchr (variable, '=') == NULL, NULL);
143
144   index = g_environ_find (envp, variable);
145   if (index != -1)
146     {
147       if (overwrite)
148         {
149           g_free (envp[index]);
150           envp[index] = g_strdup_printf ("%s=%s", variable, value);
151         }
152     }
153   else
154     {
155       gint length;
156
157       length = envp ? g_strv_length (envp) : 0;
158       envp = g_renew (gchar *, envp, length + 2);
159       envp[length] = g_strdup_printf ("%s=%s", variable, value);
160       envp[length + 1] = NULL;
161     }
162
163   return envp;
164 }
165
166 static gchar **
167 g_environ_unsetenv_internal (gchar        **envp,
168                              const gchar   *variable,
169                              gboolean       free_value)
170 {
171   gint len;
172   gchar **e, **f;
173
174   len = strlen (variable);
175
176   /* Note that we remove *all* environment entries for
177    * the variable name, not just the first.
178    */
179   e = f = envp;
180   while (*e != NULL)
181     {
182       if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
183         {
184           *f = *e;
185           f++;
186         }
187       else
188         {
189           if (free_value)
190             g_free (*e);
191         }
192
193       e++;
194     }
195   *f = NULL;
196
197   return envp;
198 }
199
200
201 /**
202  * g_environ_unsetenv:
203  * @envp: (allow-none) (array zero-terminated=1) (transfer full): an environment
204  *     list that can be freed using g_strfreev() (e.g., as returned from g_get_environ()), 
205  *     or %NULL for an empty environment list
206  * @variable: the environment variable to remove, must not contain '='
207  *
208  * Removes the environment variable @variable from the provided
209  * environment @envp.
210  *
211  * Return value: (array zero-terminated=1) (transfer full): the
212  *     updated environment list. Free it using g_strfreev().
213  *
214  * Since: 2.32
215  */
216 gchar **
217 g_environ_unsetenv (gchar       **envp,
218                     const gchar  *variable)
219 {
220   g_return_val_if_fail (variable != NULL, NULL);
221   g_return_val_if_fail (strchr (variable, '=') == NULL, NULL);
222
223   if (envp == NULL)
224     return NULL;
225
226   return g_environ_unsetenv_internal (envp, variable, TRUE);
227 }
228
229 /* UNIX implemention {{{1 */
230 #ifndef G_OS_WIN32
231
232 /**
233  * g_getenv:
234  * @variable: the environment variable to get, in the GLib file name
235  *     encoding
236  *
237  * Returns the value of an environment variable.
238  *
239  * The name and value are in the GLib file name encoding. On UNIX,
240  * this means the actual bytes which might or might not be in some
241  * consistent character set and encoding. On Windows, it is in UTF-8.
242  * On Windows, in case the environment variable's value contains
243  * references to other environment variables, they are expanded.
244  *
245  * Return value: the value of the environment variable, or %NULL if
246  *     the environment variable is not found. The returned string
247  *     may be overwritten by the next call to g_getenv(), g_setenv()
248  *     or g_unsetenv().
249  */
250 const gchar *
251 g_getenv (const gchar *variable)
252 {
253   g_return_val_if_fail (variable != NULL, NULL);
254
255   return getenv (variable);
256 }
257
258 /**
259  * g_setenv:
260  * @variable: the environment variable to set, must not contain '='.
261  * @value: the value for to set the variable to.
262  * @overwrite: whether to change the variable if it already exists.
263  *
264  * Sets an environment variable. Both the variable's name and value
265  * should be in the GLib file name encoding. On UNIX, this means that
266  * they can be arbitrary byte strings. On Windows, they should be in
267  * UTF-8.
268  *
269  * Note that on some systems, when variables are overwritten, the memory
270  * used for the previous variables and its value isn't reclaimed.
271  *
272  * <warning><para>
273  * Environment variable handling in UNIX is not thread-safe, and your
274  * program may crash if one thread calls g_setenv() while another
275  * thread is calling getenv(). (And note that many functions, such as
276  * gettext(), call getenv() internally.) This function is only safe to
277  * use at the very start of your program, before creating any other
278  * threads (or creating objects that create worker threads of their
279  * own).
280  * </para><para>
281  * If you need to set up the environment for a child process, you can
282  * use g_get_environ() to get an environment array, modify that with
283  * g_environ_setenv() and g_environ_unsetenv(), and then pass that
284  * array directly to execvpe(), g_spawn_async(), or the like.
285  * </para></warning>
286  *
287  * Returns: %FALSE if the environment variable couldn't be set.
288  *
289  * Since: 2.4
290  */
291 gboolean
292 g_setenv (const gchar *variable,
293           const gchar *value,
294           gboolean     overwrite)
295 {
296   gint result;
297 #ifndef HAVE_SETENV
298   gchar *string;
299 #endif
300
301   g_return_val_if_fail (variable != NULL, FALSE);
302   g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
303
304 #ifdef HAVE_SETENV
305   result = setenv (variable, value, overwrite);
306 #else
307   if (!overwrite && getenv (variable) != NULL)
308     return TRUE;
309
310   /* This results in a leak when you overwrite existing
311    * settings. It would be fairly easy to fix this by keeping
312    * our own parallel array or hash table.
313    */
314   string = g_strconcat (variable, "=", value, NULL);
315   result = putenv (string);
316 #endif
317   return result == 0;
318 }
319
320 #ifdef HAVE__NSGETENVIRON
321 #define environ (*_NSGetEnviron())
322 #else
323 /* According to the Single Unix Specification, environ is not
324  * in any system header, although unistd.h often declares it.
325  */
326 extern char **environ;
327 #endif
328
329 /**
330  * g_unsetenv:
331  * @variable: the environment variable to remove, must not contain '='
332  *
333  * Removes an environment variable from the environment.
334  *
335  * Note that on some systems, when variables are overwritten, the
336  * memory used for the previous variables and its value isn't reclaimed.
337  *
338  * <warning><para>
339  * Environment variable handling in UNIX is not thread-safe, and your
340  * program may crash if one thread calls g_unsetenv() while another
341  * thread is calling getenv(). (And note that many functions, such as
342  * gettext(), call getenv() internally.) This function is only safe
343  * to use at the very start of your program, before creating any other
344  * threads (or creating objects that create worker threads of their
345  * own).
346  * </para><para>
347  * If you need to set up the environment for a child process, you can
348  * use g_get_environ() to get an environment array, modify that with
349  * g_environ_setenv() and g_environ_unsetenv(), and then pass that
350  * array directly to execvpe(), g_spawn_async(), or the like.
351  * </para></warning>
352  *
353  * Since: 2.4
354  */
355 void
356 g_unsetenv (const gchar *variable)
357 {
358 #ifdef HAVE_UNSETENV
359   g_return_if_fail (variable != NULL);
360   g_return_if_fail (strchr (variable, '=') == NULL);
361
362   unsetenv (variable);
363 #else /* !HAVE_UNSETENV */
364   g_return_if_fail (variable != NULL);
365   g_return_if_fail (strchr (variable, '=') == NULL);
366
367   /* Mess directly with the environ array.
368    * This seems to be the only portable way to do this.
369    */
370   g_environ_unsetenv_internal (environ, variable, FALSE);
371 #endif /* !HAVE_UNSETENV */
372 }
373
374 /**
375  * g_listenv:
376  *
377  * Gets the names of all variables set in the environment.
378  *
379  * Programs that want to be portable to Windows should typically use
380  * this function and g_getenv() instead of using the environ array
381  * from the C library directly. On Windows, the strings in the environ
382  * array are in system codepage encoding, while in most of the typical
383  * use cases for environment variables in GLib-using programs you want
384  * the UTF-8 encoding that this function and g_getenv() provide.
385  *
386  * Returns: (array zero-terminated=1) (transfer full): a %NULL-terminated
387  *     list of strings which must be freed with g_strfreev().
388  *
389  * Since: 2.8
390  */
391 gchar **
392 g_listenv (void)
393 {
394   gchar **result, *eq;
395   gint len, i, j;
396
397   len = g_strv_length (environ);
398   result = g_new0 (gchar *, len + 1);
399
400   j = 0;
401   for (i = 0; i < len; i++)
402     {
403       eq = strchr (environ[i], '=');
404       if (eq)
405         result[j++] = g_strndup (environ[i], eq - environ[i]);
406     }
407
408   result[j] = NULL;
409
410   return result;
411 }
412
413 /**
414  * g_get_environ:
415  *
416  * Gets the list of environment variables for the current process.
417  *
418  * The list is %NULL terminated and each item in the list is of the
419  * form 'NAME=VALUE'.
420  *
421  * This is equivalent to direct access to the 'environ' global variable,
422  * except portable.
423  *
424  * The return value is freshly allocated and it should be freed with
425  * g_strfreev() when it is no longer needed.
426  *
427  * Returns: (array zero-terminated=1) (transfer full): the list of
428  *     environment variables
429  *
430  * Since: 2.28
431  */
432 gchar **
433 g_get_environ (void)
434 {
435   return g_strdupv (environ);
436 }
437
438 /* Win32 implementation {{{1 */
439 #else   /* G_OS_WIN32 */
440
441 const gchar *
442 g_getenv (const gchar *variable)
443 {
444   GQuark quark;
445   gchar *value;
446   wchar_t dummy[2], *wname, *wvalue;
447   int len;
448
449   g_return_val_if_fail (variable != NULL, NULL);
450   g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
451
452   /* On Windows NT, it is relatively typical that environment
453    * variables contain references to other environment variables. If
454    * so, use ExpandEnvironmentStrings(). (In an ideal world, such
455    * environment variables would be stored in the Registry as
456    * REG_EXPAND_SZ type values, and would then get automatically
457    * expanded before a program sees them. But there is broken software
458    * that stores environment variables as REG_SZ values even if they
459    * contain references to other environment variables.)
460    */
461
462   wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
463
464   len = GetEnvironmentVariableW (wname, dummy, 2);
465
466   if (len == 0)
467     {
468       g_free (wname);
469       return NULL;
470     }
471   else if (len == 1)
472     len = 2;
473
474   wvalue = g_new (wchar_t, len);
475
476   if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
477     {
478       g_free (wname);
479       g_free (wvalue);
480       return NULL;
481     }
482
483   if (wcschr (wvalue, L'%') != NULL)
484     {
485       wchar_t *tem = wvalue;
486
487       len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
488
489       if (len > 0)
490         {
491           wvalue = g_new (wchar_t, len);
492
493           if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
494             {
495               g_free (wvalue);
496               wvalue = tem;
497             }
498           else
499             g_free (tem);
500         }
501     }
502
503   value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
504
505   g_free (wname);
506   g_free (wvalue);
507
508   quark = g_quark_from_string (value);
509   g_free (value);
510
511   return g_quark_to_string (quark);
512 }
513
514 gboolean
515 g_setenv (const gchar *variable,
516           const gchar *value,
517           gboolean     overwrite)
518 {
519   gboolean retval;
520   wchar_t *wname, *wvalue, *wassignment;
521   gchar *tem;
522
523   g_return_val_if_fail (variable != NULL, FALSE);
524   g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
525   g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
526   g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
527
528   if (!overwrite && g_getenv (variable) != NULL)
529     return TRUE;
530
531   /* We want to (if possible) set both the environment variable copy
532    * kept by the C runtime and the one kept by the system.
533    *
534    * We can't use only the C runtime's putenv or _wputenv() as that
535    * won't work for arbitrary Unicode strings in a "non-Unicode" app
536    * (with main() and not wmain()). In a "main()" app the C runtime
537    * initializes the C runtime's environment table by converting the
538    * real (wide char) environment variables to system codepage, thus
539    * breaking those that aren't representable in the system codepage.
540    *
541    * As the C runtime's putenv() will also set the system copy, we do
542    * the putenv() first, then call SetEnvironmentValueW ourselves.
543    */
544
545   wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
546   wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
547   tem = g_strconcat (variable, "=", value, NULL);
548   wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
549
550   g_free (tem);
551   _wputenv (wassignment);
552   g_free (wassignment);
553
554   retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
555
556   g_free (wname);
557   g_free (wvalue);
558
559   return retval;
560 }
561
562 void
563 g_unsetenv (const gchar *variable)
564 {
565   wchar_t *wname, *wassignment;
566   gchar *tem;
567
568   g_return_if_fail (variable != NULL);
569   g_return_if_fail (strchr (variable, '=') == NULL);
570   g_return_if_fail (g_utf8_validate (variable, -1, NULL));
571
572   wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
573   tem = g_strconcat (variable, "=", NULL);
574   wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
575
576   g_free (tem);
577   _wputenv (wassignment);
578   g_free (wassignment);
579
580   SetEnvironmentVariableW (wname, NULL);
581
582   g_free (wname);
583 }
584
585 gchar **
586 g_listenv (void)
587 {
588   gchar **result, *eq;
589   gint len = 0, j;
590   wchar_t *p, *q;
591
592   p = (wchar_t *) GetEnvironmentStringsW ();
593   if (p != NULL)
594     {
595       q = p;
596       while (*q)
597         {
598           q += wcslen (q) + 1;
599           len++;
600         }
601     }
602   result = g_new0 (gchar *, len + 1);
603
604   j = 0;
605   q = p;
606   while (*q)
607     {
608       result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
609       if (result[j] != NULL)
610         {
611           eq = strchr (result[j], '=');
612           if (eq && eq > result[j])
613             {
614               *eq = '\0';
615               j++;
616             }
617           else
618             g_free (result[j]);
619         }
620       q += wcslen (q) + 1;
621     }
622   result[j] = NULL;
623   FreeEnvironmentStringsW (p);
624
625   return result;
626 }
627
628 gchar **
629 g_get_environ (void)
630 {
631   gunichar2 *strings;
632   gchar **result;
633   gint i, n;
634
635   strings = GetEnvironmentStringsW ();
636   for (n = 0; strings[n]; n += wcslen (strings + n) + 1);
637   result = g_new (char *, n + 1);
638   for (i = 0; strings[i]; i += wcslen (strings + i) + 1)
639     result[i] = g_utf16_to_utf8 (strings + i, -1, NULL, NULL, NULL);
640   FreeEnvironmentStringsW (strings);
641   result[i] = NULL;
642
643   return result;
644 }
645
646 /* Win32 binary compatibility versions {{{1 */
647 #ifndef _WIN64
648
649 #undef g_getenv
650
651 const gchar *
652 g_getenv (const gchar *variable)
653 {
654   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
655   const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
656   gchar *value;
657   GQuark quark;
658
659   g_free (utf8_variable);
660   if (!utf8_value)
661     return NULL;
662   value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
663   quark = g_quark_from_string (value);
664   g_free (value);
665
666   return g_quark_to_string (quark);
667 }
668
669 #undef g_setenv
670
671 gboolean
672 g_setenv (const gchar *variable,
673           const gchar *value,
674           gboolean     overwrite)
675 {
676   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
677   gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
678   gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
679
680   g_free (utf8_variable);
681   g_free (utf8_value);
682
683   return retval;
684 }
685
686 #undef g_unsetenv
687
688 void
689 g_unsetenv (const gchar *variable)
690 {
691   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
692
693   g_unsetenv_utf8 (utf8_variable);
694
695   g_free (utf8_variable);
696 }
697
698 #endif  /* _WIN64 */
699
700 #endif  /* G_OS_WIN32 */
701
702 /* Epilogue {{{1 */
703 /* vim: set foldmethod=marker: */