1
0
mirror of https://github.com/rkd77/elinks.git synced 2024-12-04 14:46:47 -05:00
elinks/src/util/env.c

79 lines
1.5 KiB
C
Raw Normal View History

2007-07-27 05:35:13 -04:00
/** Environment variables handling
* @file */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "elinks.h"
#include "util/env.h"
#include "util/memory.h"
#include "util/string.h"
2007-07-27 05:35:13 -04:00
/** Set @a name environment variable to @a value or a substring of it:
* On success, it returns 0.
2007-07-27 05:35:13 -04:00
* If @a value is NULL and on error, it returns -1.
* If @a length >= 0 and smaller than true @a value length, it will
* set @a name to specified substring of @a value.
*/
int
2022-02-17 14:11:45 -05:00
env_set(const char *name, const char *value, int length)
{
int true_length, substring = 0;
if (!value || !name || !*name) return -1;
true_length = strlen(value);
substring = (length >= 0 && length < true_length);
if (!substring) length = true_length;
#if defined(HAVE_SETENV)
{
2022-02-17 14:11:45 -05:00
if (!substring) {
return setenv(name, value, 1);
} else {
/* Copy the substring. */
2022-02-17 14:11:45 -05:00
char *v = memacpy(value, length);
if (v) {
int ret = setenv(name, v, 1);
mem_free(v);
2022-02-17 14:11:45 -05:00
return ret;
}
return -1;
}
}
#elif defined(HAVE_PUTENV)
{
int namelen = strlen(name);
char *s = malloc(namelen + length + 2);
if (!s) return -1;
memcpy(s, name, namelen);
s[namelen] = '=';
memcpy(&s[namelen + 1], value, length);
s[namelen + 1 + length] = '\0';
/* @s is never freed by us, this is intentional.
* --> Possible memleaks on repeated use of
* this function. */
return putenv(s);
}
#else
/* XXX: what to do ?? */
return -1;
#endif
}