environment grooming
[exim.git] / src / src / environment.c
1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
4
5 /* Copyright (c) Heiko Schlittermann 2016
6 * hs@schlittermann.de
7 * See the file NOTICE for conditions of use and distribution.
8 */
9
10 #include "exim.h"
11
12 extern char **environ;
13
14 /* The cleanup_environment() function is used during the startup phase
15 of the Exim process, right after reading the configurations main
16 part, before any expansions take place. It retains the environment
17 variables we trust (via the keep_environment option) and allows to
18 set additional variables (via add_environment).
19
20 Returns: TRUE if successful
21 FALSE otherwise
22 */
23
24 BOOL
25 cleanup_environment()
26 {
27 if (!keep_environment || *keep_environment == '\0')
28 {
29 /* From: https://github.com/dovecot/core/blob/master/src/lib/env-util.c#L55
30 Try to clear the environment.
31 a) environ = NULL crashes on OS X.
32 b) *environ = NULL doesn't work on FreeBSD 7.0.
33 c) environ = emptyenv doesn't work on Haiku OS
34 d) environ = calloc() should work everywhere */
35
36 if (environ) *environ = NULL;
37
38 }
39 else if (Ustrcmp(keep_environment, "*") != 0)
40 {
41 rmark reset_point = store_mark();
42 if (environ) for (uschar ** p = USS environ; *p; /* see below */)
43 {
44 /* It's considered broken if we do not find the '=', according to
45 Florian Weimer. For now we ignore such strings. unsetenv() would complain,
46 getenv() would complain. */
47 uschar * eqp = Ustrchr(*p, '=');
48
49 if (eqp)
50 {
51 uschar * name = string_copyn(*p, eqp - *p);
52
53 if (OK != match_isinlist(name, CUSS &keep_environment,
54 0, NULL, NULL, MCL_NOEXPAND, FALSE, NULL))
55 if (os_unsetenv(name) < 0) return FALSE;
56 else p = USS environ; /* RESTART from the beginning */
57 else p++;
58 }
59 }
60 store_reset(reset_point);
61 }
62 #ifndef DISABLE_TLS
63 tls_clean_env();
64 #endif
65 if (add_environment)
66 {
67 uschar * p;
68 int sep = 0;
69 const uschar * envlist = add_environment;
70
71 while ((p = string_nextinlist(&envlist, &sep, NULL, 0))) putenv(CS p);
72 }
73
74 return TRUE;
75 }