1 /*	$NetBSD: clean_env.c,v 1.1.1.1 2009/06/23 10:08:59 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	clean_env 3
6 /* SUMMARY
7 /*	clean up the environment
8 /* SYNOPSIS
9 /*	#include <clean_env.h>
10 /*
11 /*	void	clean_env(preserve_list)
12 /*	const char **preserve_list;
13 /* DESCRIPTION
14 /*	clean_env() reduces the process environment to the bare minimum.
15 /*	The function takes a null-terminated list of arguments.
16 /*	Each argument specifies the name of an environment variable
17 /*	that should be preserved, or specifies a name=value that should
18 /*	be entered into the new environment.
19 /* DIAGNOSTICS
20 /*	Fatal error: out of memory.
21 /* SEE ALSO
22 /*	safe_getenv(3), guarded getenv()
23 /* LICENSE
24 /* .ad
25 /* .fi
26 /*	The Secure Mailer license must be distributed with this software.
27 /* AUTHOR(S)
28 /*	Wietse Venema
29 /*	IBM T.J. Watson Research
30 /*	P.O. Box 704
31 /*	Yorktown Heights, NY 10598, USA
32 /*--*/
33 
34 /* System library. */
35 
36 #include <sys_defs.h>
37 #include <stdlib.h>
38 #include <unistd.h>
39 #include <string.h>
40 
41 /* Utility library. */
42 
43 #include <msg.h>
44 #include <argv.h>
45 #include <safe.h>
46 #include <clean_env.h>
47 
48 /* clean_env - clean up the environment */
49 
50 void    clean_env(char **preserve_list)
51 {
52     extern char **environ;
53     ARGV   *save_list;
54     char   *value;
55     char  **cpp;
56     char   *eq;
57 
58     /*
59      * Preserve or specify selected environment variables.
60      */
61 #define STRING_AND_LENGTH(x, y) (x), (ssize_t) (y)
62 
63     save_list = argv_alloc(10);
64     for (cpp = preserve_list; *cpp; cpp++)
65 	if ((eq = strchr(*cpp, '=')) != 0)
66 	    argv_addn(save_list, STRING_AND_LENGTH(*cpp, eq - *cpp),
67 		      STRING_AND_LENGTH(eq + 1, strlen(eq + 1)), (char *) 0);
68 	else if ((value = safe_getenv(*cpp)) != 0)
69 	    argv_add(save_list, *cpp, value, (char *) 0);
70 
71     /*
72      * Truncate the process environment, if available. On some systems
73      * (Ultrix!), environ can be a null pointer.
74      */
75     if (environ)
76 	environ[0] = 0;
77 
78     /*
79      * Restore preserved environment variables.
80      */
81     for (cpp = save_list->argv; *cpp; cpp += 2)
82 	if (setenv(cpp[0], cpp[1], 1))
83 	    msg_fatal("setenv(%s, %s): %m", cpp[0], cpp[1]);
84 
85     /*
86      * Cleanup.
87      */
88     argv_free(save_list);
89 }
90