1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
|
#define _DEFAULT_SOURCE
#define _POSIX_C_SOURCE 200809L
#include "utils/env.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "utils/libstring.h"
void env_set(const char *name, const char *value)
{
if (setenv(name, value, 1) == -1)
{
fprintf(stderr, "env_set: unable to set \'%s\'=\'%s\'.\n", name, value);
}
}
void env_unset(const char *name)
{
if (unsetenv(name) == -1)
{
fprintf(stderr, "env_unset: unable to unset \'%s\'.\n", name);
}
}
static void _generate_random(void)
{
int d = rand() % MAX_RAND;
char buf[16] = { 0 };
sprintf(buf, "%d", d);
env_set("RANDOM", buf);
}
static struct string *_cat_args(void)
{
int nb_args = atoi(env_get("#"));
struct string *s = string_create(NULL);
for (int i = 1; i <= nb_args; i++)
{
char buf[16] = { 0 };
sprintf(buf, "%d", i);
string_pushstr(s, env_get(buf));
if (i != nb_args)
{
string_pushc(s, ' ');
}
}
return s;
}
char *env_get(const char *name)
{
if (STRINGS_ARE_EQUAL(name, "RANDOM"))
{
_generate_random();
}
if (STRINGS_ARE_EQUAL(name, "*"))
{
struct string *s = _cat_args();
env_set("*", s->data);
string_free(s);
}
if (STRINGS_ARE_EQUAL(name, "@"))
{
struct string *s = string_create(NULL);
string_pushc(s, '\"');
struct string *args = _cat_args();
string_pushstr(s, args->data);
string_pushc(s, '\"');
if (s->length > 2)
{
env_set("@", s->data);
}
string_free(s);
string_free(args);
}
return getenv(name);
}
void env_clear(void)
{
if (clearenv())
{
fprintf(stderr, "env_clear: unable to clear the environment.\n");
}
}
static void _set_pwd(void)
{
char buf[MAX_PATH_SIZE] = { 0 };
char *path = getcwd(buf, MAX_PATH_SIZE);
env_set("PWD", path);
env_set("OLDPWD", path);
}
static void _set_uid(void)
{
uid_t uid = getuid();
// Magic value but UID is an integer (POSIX requirement)
// So it won't be more that 10 chars long
char buf[16] = { 0 };
sprintf(buf, "%u", uid);
env_set("UID", buf);
}
static void _set_pid(void)
{
pid_t pid = getpid();
// Magic value but PID is an integer (POSIX requirement)
// So it won't be more that 10 chars long
char buf[16] = { 0 };
sprintf(buf, "%d", pid);
env_set("$", buf);
}
void env_setup(void)
{
_set_pwd();
_set_uid();
_set_pid();
env_set("IFS", DEFAULT_IFS);
env_set("?", "0");
}
|