toaruos/libc/stdlib/putenv.c

85 lines
1.6 KiB
C
Raw Normal View History

2018-05-02 13:25:03 +03:00
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
extern char ** environ;
extern int _environ_size;
static int why_no_strnstr(char * a, char * b, int n) {
for (int i = 0; (i < n) && (a[i]) && (b[i]); ++i) {
if (a[i] != b[i]) {
return 1;
}
}
return 0;
}
2018-09-23 05:58:07 +03:00
int unsetenv(const char * str) {
int last_index = -1;
int found_index = -1;
int len = strlen(str);
for (int i = 0; environ[i]; ++i) {
if (found_index == -1 && (strstr(environ[i], str) == environ[i] && environ[i][len] == '=')) {
found_index = i;
}
last_index = i;
}
if (found_index == -1) {
/* not found = success */
return 0;
}
if (last_index == found_index) {
/* Was last element */
environ[last_index] = NULL;
return 0;
}
/* Was not last element, swap ordering */
environ[found_index] = environ[last_index];
environ[last_index] = NULL;
return 0;
}
2018-05-02 13:25:03 +03:00
int putenv(char * string) {
2021-05-31 04:47:02 +03:00
char name[strlen(string)+1];
2018-05-02 13:25:03 +03:00
strcpy(name, string);
char * c = strchr(name, '=');
if (!c) {
return 1;
}
*c = NULL;
int s = strlen(name);
int i;
2018-08-14 08:39:48 +03:00
for (i = 0; i < (_environ_size - 1) && environ[i]; ++i) {
2018-09-23 05:58:07 +03:00
if (!why_no_strnstr(name, environ[i], s) && environ[i][s] == '=') {
2018-05-02 13:25:03 +03:00
environ[i] = string;
return 0;
}
}
/* Not found */
2018-08-14 08:39:48 +03:00
if (i == _environ_size - 1) {
int _new_environ_size = _environ_size * 2;
char ** new_environ = malloc(sizeof(char*) * _new_environ_size);
int j = 0;
while (j < _new_environ_size && environ[j]) {
new_environ[j] = environ[j];
j++;
}
while (j < _new_environ_size) {
new_environ[j] = NULL;
j++;
2018-05-02 13:25:03 +03:00
}
2018-08-14 08:39:48 +03:00
_environ_size = _new_environ_size;
environ = new_environ;
2018-05-02 13:25:03 +03:00
}
environ[i] = string;
return 0;
}