New action: move-cursor-line-start.
[elinks/kon.git] / src / util / env.c
blobd9bc42c8f087270a4f432a7acd4450f41dbb01ae
1 /** Environment variables handling
2 * @file */
4 #ifdef HAVE_CONFIG_H
5 #include "config.h"
6 #endif
8 #include <ctype.h>
9 #include <errno.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
14 #include "elinks.h"
16 #include "util/env.h"
17 #include "util/memory.h"
18 #include "util/string.h"
20 /** Set @a name environment variable to @a value or a substring of it:
21 * On success, it returns 0.
22 * If @a value is NULL and on error, it returns -1.
23 * If @a length >= 0 and smaller than true @a value length, it will
24 * set @a name to specified substring of @a value.
26 int
27 env_set(unsigned char *name, unsigned char *value, int length)
29 int true_length, substring = 0;
31 if (!value || !name || !*name) return -1;
33 true_length = strlen(value);
34 substring = (length >= 0 && length < true_length);
35 if (!substring) length = true_length;
37 #if defined(HAVE_SETENV)
39 int ret, allocated = 0;
41 if (substring) {
42 /* Copy the substring. */
43 value = memacpy(value, length);
44 if (!value) return -1;
45 allocated = 1;
48 ret = setenv(name, value, 1);
49 if (allocated) mem_free(value);
50 return ret;
53 #elif defined(HAVE_PUTENV)
56 int namelen = strlen(name);
57 char *s = malloc(namelen + length + 2);
59 if (!s) return -1;
60 memcpy(s, name, namelen);
61 s[namelen] = '=';
62 memcpy(&s[namelen + 1], value, length);
63 s[namelen + 1 + length] = '\0';
65 /* @s is never freed by us, this is intentional.
66 * --> Possible memleaks on repeated use of
67 * this function. */
68 return putenv(s);
71 #else
72 /* XXX: what to do ?? */
73 return -1;
74 #endif