]> diplodocus.org Git - nmh/blob - sbr/putenv.c
Reverted commit 9a4b4a3d3b27fe4a7ff6d0b8724ce1c06b5917eb.
[nmh] / sbr / putenv.c
1
2 /*
3 * putenv.c -- (un)set an envariable
4 *
5 * This code is Copyright (c) 2002, by the authors of nmh. See the
6 * COPYRIGHT file in the root directory of the nmh distribution for
7 * complete copyright information.
8 */
9
10 #include <h/mh.h>
11 #include <h/utils.h>
12
13 extern char **environ;
14
15 /*
16 * prototypes
17 */
18 int m_putenv (char *, char *);
19 int unputenv (char *);
20 static int nvmatch (char *, char *);
21
22 /* FIXME: These functions leak memory. No easy fix since they might not
23 * be malloc'd. Switch to setenv(3) and unsetenv(3). */
24
25 int
26 m_putenv (char *name, char *value)
27 {
28 int i;
29 char **ep, **nep, *cp;
30
31 cp = concat(name, "=", value, NULL);
32
33 for (ep = environ, i = 0; *ep; ep++, i++)
34 if (nvmatch (name, *ep)) {
35 *ep = cp;
36 return 0;
37 }
38
39 nep = (char **) mh_xmalloc ((size_t) ((i + 2) * sizeof(*nep)));
40
41 for (ep = environ, i = 0; *ep; nep[i++] = *ep++)
42 continue;
43 nep[i++] = cp;
44 nep[i] = NULL;
45 environ = nep;
46 return 0;
47 }
48
49
50 int
51 unputenv (char *name)
52 {
53 char **ep, **nep;
54
55 for (ep = environ; *ep; ep++)
56 if (nvmatch (name, *ep))
57 break;
58 if (*ep == NULL)
59 return 1;
60
61 for (nep = ep + 1; *nep; nep++)
62 continue;
63 *ep = *--nep;
64 *nep = NULL;
65 return 0;
66 }
67
68
69 static int
70 nvmatch (char *s1, char *s2)
71 {
72 while (*s1 == *s2++)
73 if (*s1++ == '=')
74 return 1;
75
76 return (*s1 == '\0' && *--s2 == '=');
77 }