#include "cron.h"
char **
env_init(void)
{
char **p;
p = malloc(sizeof(char *));
if (p)
p[0] = NULL;
return (p);
}
void
env_free(char **envp)
{
char **p;
for (p = envp; *p; p++)
free(*p);
free(envp);
}
char **
env_copy(char **envp)
{
int count, i;
char **p;
for (count = 0; envp[count] != NULL; count++)
;
p = (char **) malloc((count+1) * sizeof(char *));
if (p == NULL) {
errno = ENOMEM;
return NULL;
}
for (i = 0; i < count; i++)
if ((p[i] = strdup(envp[i])) == NULL) {
while (--i >= 0)
free(p[i]);
free(p);
errno = ENOMEM;
return NULL;
}
p[count] = NULL;
return (p);
}
char **
env_set(char **envp, char *envstr)
{
int count, found;
char **p;
char *q;
found = -1;
for (count = 0; envp[count] != NULL; count++) {
if (!strcmp_until(envp[count], envstr, '='))
found = count;
}
count++;
if (found != -1) {
q = envp[found];
if ((envp[found] = strdup(envstr)) == NULL) {
envp[found] = q;
errno = ENOMEM;
return NULL;
}
free(q);
return (envp);
}
p = (char **) realloc((void *) envp,
(unsigned) ((count+1) * sizeof(char *)));
if (p == NULL) {
errno = ENOMEM;
return NULL;
}
p[count] = p[count-1];
if ((p[count-1] = strdup(envstr)) == NULL) {
env_free(p);
errno = ENOMEM;
return NULL;
}
return (p);
}
int
load_env(char *envstr, FILE *f)
{
long filepos;
int fileline;
char name[MAX_ENVSTR], val[MAX_ENVSTR];
int fields;
filepos = ftell(f);
fileline = LineNumber;
skip_comments(f);
if (EOF == get_string(envstr, MAX_ENVSTR, f, "\n"))
return (ERR);
Debug(DPARS, ("load_env, read <%s>\n", envstr))
name[0] = val[0] = '\0';
fields = sscanf(envstr, "%[^ =] = %[^\n#]", name, val);
if (fields != 2) {
Debug(DPARS, ("load_env, not 2 fields (%d)\n", fields))
fseek(f, filepos, 0);
Set_LineNum(fileline);
return (FALSE);
}
{
int len = strdtb(val);
if (len >= 2) {
if (val[0] == '\'' || val[0] == '"') {
if (val[len-1] == val[0]) {
val[len-1] = '\0';
strcpy(val, val+1);
}
}
}
}
if (strlen(name) + 1 + strlen(val) >= MAX_ENVSTR-1)
return (FALSE);
sprintf(envstr, "%s=%s", name, val);
Debug(DPARS, ("load_env, <%s> <%s> -> <%s>\n", name, val, envstr))
return (TRUE);
}
char *
env_get(const char *name, char **envp)
{
int len;
char *p, *q;
len = strlen(name);
while ((p = *envp++)) {
if (!(q = strchr(p, '=')))
continue;
if ((q - p) == len && !strncmp(p, name, len))
return (q+1);
}
return (NULL);
}