aboutsummaryrefslogtreecommitdiff
path: root/lib/environment.c
blob: d9419f0821a171d50306ba19568dc464d989af40 (plain) (blame)
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/**
 * @file environment.c
 */
#include "spm.h"

/**
 * Print a shell-specific listing of environment variables to `stdout`
 *
 * Example:
 * ~~~{.c}
 * int main(int argc, char *argv[], char *arge[]) {
 *     RuntimeEnv *rt = runtime_copy(arge);
 *     runtime_export(rt, NULL);
 *     runtime_free(rt);
 *     return 0;
 * }
 * ~~~
 *
 * Usage:
 * ~~~{.sh}
 * $ gcc program.c
 * $ ./a.out
 * PATH="/thing/stuff/bin:/example/please/bin"
 * SHELL="/your/shell"
 * CC="/your/compiler"
 * ...=...
 *
 * # You can also use this to modify the shell environment
 * # (use `runtime_set` to manipulate the output)
 * $ source $(./a.out)
 * ~~~
 *
 * Example of exporting specific keys from the environment:
 *
 * ~~~{.c}
 * int main(int argc, char *argv[], char *arge[]) {
 *     RuntimeEnv *rt = runtime_copy(arge);
 *
 *     // inline declaration
 *     runtime_export(rt, (char *[]) {"PATH", "LS_COLORS", NULL});
 *
 *     // standard declaration
 *     char *keys_to_export[] = {
 *         "PATH", "LS_COLORS", NULL
 *     }
 *     runtime_export(rt, keys_to_export);
 *
 *     runtime_free(rt);
 *     return 0;
 * }
 * ~~~
 *
 * @param env `RuntimeEnv` structure
 * @param keys Array of keys to export. A value of `NULL` exports all environment keys
 */
void runtime_export(RuntimeEnv *env, char **keys) {
    char *borne[] = {
            "bash",
            "dash",
            "zsh",
            NULL,
    };
    char *unborne[] = {
            "csh"
            "tcsh",
            NULL,
    };

    char output[BUFSIZ];
    char export_command[7]; // export=6 and setenv=6... convenient
    char *_sh = getenv("SHELL");
    char *sh = basename(_sh);
    if (sh == NULL) {
        fprintf(stderr, "echo SHELL environment variable is not defined");
        exit(1);
    }

    for (size_t i = 0; borne[i] != NULL; i++) {
        if (strcmp(sh, borne[i]) == 0) {
            strcpy(export_command, "export");
            break;
        }
    }
    for (size_t i = 0; unborne[i] != NULL; i++) {
        if (strcmp(sh, unborne[i]) == 0) {
            strcpy(export_command, "setenv");
            break;
        }
    }

    for (size_t i = 0; i < strlist_count(env); i++) {
        char **pair = split(strlist_item(env, i), "=");
        char *key = pair[0];
        char *value = NULL;

        // We split a potentially large string by "=" so:
        // Recombine elements pair[1..N] into a single string by "="
        if (pair[1] != NULL) {
            value = join(&pair[1], "=");
        }

        if (keys != NULL) {
            for (size_t j = 0; keys[j] != NULL; j++) {
                if (strcmp(keys[j], key) == 0) {
                    sprintf(output, "%s=\"%s\"\n%s %s", key, value ? value : "", export_command, key);
                    puts(output);
                }
            }
        }
        else {
            sprintf(output, "%s=\"%s\"\n%s %s", key, value ? value : "", export_command, key);
            puts(output);
        }
        free(value);
        split_free(pair);
    }
}

/**
 * Populate a `RuntimeEnv` structure
 *
 * Example:
 *
 * ~~~{.c}
 * int main(int argc, char *argv[], char *arge[]) {
 *     RuntimeEnv *rt = NULL;
 *     // Example 1: Copy the shell environment
 *     rt = runtime_copy(arge);
 *     // Example 2: Create your own environment
 *     rt = runtime_copy((char *[]) {"SHELL=/bin/bash", "PATH=/opt/secure:/bin:/usr/bin"})
 *
 *     runtime_free(rt);
 *     return 0;
 * }
 * ~~~
 *
 * @param env Array of strings in `var=value` format
 * @return `RuntimeEnv` structure
 */
RuntimeEnv *runtime_copy(char **env) {
    RuntimeEnv *rt = NULL;
    size_t env_count;
    for (env_count = 0; env[env_count] != NULL; env_count++);

    rt = strlist_init();
    for (size_t i = 0; i < env_count; i++) {
        strlist_append(rt, env[i]);
    }
    return rt;
}

/**
 * Determine whether or not a key exists in the runtime environment
 *
 * Example:
 *
 * ~~~{.c}
 * int main(int argc, char *argv[], char *arge[]) {
 *     RuntimeEnv *rt = runtime_copy(arge);
 *     if (runtime_contains(rt, "PATH") {
 *         // $PATH is present
 *     }
 *     else {
 *         // $PATH is NOT present
 *     }
 *
 *     runtime_free(rt);
 *     return 0;
 * }
 * ~~~
 *
 * @param env `RuntimeEnv` structure
 * @param key Environment variable string
 * @return  -1=no, positive_value=yes
 */
ssize_t runtime_contains(RuntimeEnv *env, const char *key) {
    ssize_t result = -1;
    for (size_t i = 0; i < strlist_count(env); i++) {
        char **pair = split(strlist_item(env, i), "=");
        if (pair == NULL) {
            break;
        }
        if (strcmp(pair[0], key) == 0) {
            result = i;
            split_free(pair);
            break;
        }
        split_free(pair);
    }
    return result;
}

/**
 * Retrieve the value of a runtime environment variable
 *
 * Example:
 *
 * ~~~{.c}
 * int main(int argc, char *argv[], char *arge[]) {
 *     RuntimeEnv *rt = runtime_copy(arge);
 *     char *path = runtime_get("PATH");
 *     if (path == NULL) {
 *         // handle error
 *     }
 *
 *     runtime_free(rt);
 *     return 0;
 * }
 * ~~~
 *
 * @param env `RuntimeEnv` structure
 * @param key Environment variable string
 * @return success=string, failure=`NULL`
 */
char *runtime_get(RuntimeEnv *env, const char *key) {
    char *result = NULL;
    ssize_t key_offset = runtime_contains(env, key);
    if (key_offset != -1) {
        char **pair = split(strlist_item(env, key_offset), "=");
        result = join(&pair[1], "=");
        split_free(pair);
    }
    return result;
}

/**
 * Parse an input string and expand any environment variable(s) found
 *
 * Example:
 *
 * ~~~{.c}
 * int main(int argc, char *argv[], char *arge[]) {
 *     RuntimeEnv *rt = runtime_copy(arge);
 *     char *secure_path = runtime_expand_var(rt, "/opt/secure:$PATH:/aux/bin");
 *     if (secure_path == NULL) {
 *         // handle error
 *     }
 *     // secure_path = "/opt/secure:/your/original/path/here:/aux/bin");
 *
 *     runtime_free(rt);
 *     return 0;
 * }
 * ~~~
 *
 * @param env `RuntimeEnv` structure
 * @param input String to parse
 * @return success=expanded string, failure=`NULL`
 */
char *runtime_expand_var(RuntimeEnv *env, const char *input) {
    const char delim = '$';
    const char *delim_literal = "$$";
    char *expanded = NULL;

    // If there's no environment variables to process return a copy of the input string
    if (strchr(input, delim) == NULL) {
        return strdup(input);
    }

    expanded = calloc(BUFSIZ, sizeof(char));
    if (expanded == NULL) {
        perror("could not allocate runtime_expand_var buffer");
        fprintf(SYSERROR);
        return NULL;
    }

    // Parse the input string
    size_t i;
    for (i = 0; i < strlen(input); i++) {
        char var[MAXNAMLEN];    // environment variable name
        memset(var, '\0', MAXNAMLEN);   // zero out name

        // Handle literal statement "$$var"
        // Value becomes "$var" (unexpanded)
        if (strncmp(&input[i], delim_literal, strlen(delim_literal)) == 0) {
            strncat(expanded, &delim, 1);
            i += strlen(delim_literal);
            // Ignore opening brace
            if (input[i] == '{') {
                i++;
            }
        }

        // Handle variable when encountering a single $
        // Value expands from "$var" to "environment value of var"
        if (input[i] == delim) {
            // Ignore opening brace
            if (input[i+1] == '{') {
                i++;
            }
            char *tmp = NULL;
            i++;

            // Construct environment variable name from input
            // "$ var" == no
            // "$-*)!@ == no
            // "$var" == yes
            for (size_t c = 0; isalnum(input[i]) || input[i] == '_'; c++, i++) {
                // Ignore closing brace
                if (input[i] == '}') {
                    i++;
                }
                var[c] = input[i];
            }

            tmp = runtime_get(env, var);
            if (tmp == NULL) {
                // This mimics shell behavior in general.
                // Prevent appending whitespace when an environment variable does not exist
                if (i > 0) {
                    i--;
                }
                continue;
            }
            // Append expanded environment variable to output
            strncat(expanded, tmp, strlen(tmp));
            free(tmp);
        }

        // Nothing to do so append input to output
        if (input[i] == '}') {
            // Unless we ended on a closing brace
            continue;
        }
        strncat(expanded, &input[i], 1);
    }

    return expanded;
}

/**
 * Set a runtime environment variable.
 *
 *
 * Note: `_value` is passed through `runtime_expand_var` to provide shell expansion
 *
 *
 * Example:
 *
 * ~~~{.c}
 * int main(int argc, char *argv[], char *arge[]) {
 *     RuntimeEnv *rt = runtime_copy(arge);
 *
 *     runtime_set(rt, "new_var", "1");
 *     char *new_var = runtime_get("new_var");
 *     // new_var = 1;
 *
 *     char *path = runtime_get("PATH");
 *     // path = /your/path:/here
 *
 *     runtime_set(rt, "PATH", "/opt/secure:$PATH");
 *     char *secure_path = runtime_get("PATH");
 *     // secure_path = /opt/secure:/your/path:/here
 *     // NOTE: path and secure_path are COPIES, unlike `getenv()` and `setenv()` that reuse their pointers in `environ`
 *
 *     runtime_free(rt);
 *     return 0;
 * }
 * ~~~
 *
 *
 * @param env `RuntimeEnv` structure
 * @param _key Environment variable to set
 * @param _value New environment variable value
 */
void runtime_set(RuntimeEnv *env, const char *_key, const char *_value) {
    if (_key == NULL) {
        return;
    }
    char *key = strdup(_key);
    ssize_t key_offset = runtime_contains(env, key);
    char *value = runtime_expand_var(env, _value);
    char *now = join((char *[]) {key, value, NULL}, "=");

    if (key_offset < 0) {
        strlist_append(env, now);
    }
    else {
        strlist_set(env, key_offset, now);
    }
    free(now);
    free(key);
    free(value);
}

/**
 * Update the global `environ` array with data from `RuntimeEnv`
 * @param env `RuntimeEnv` structure
 */
void runtime_apply(RuntimeEnv *env) {
    for (size_t i = 0; i < strlist_count(env); i++) {
        char **pair = split(strlist_item(env, i), "=");
        setenv(pair[0], pair[1], 1);
        split_free(pair);
    }
}

/**
 * Free `RuntimeEnv` allocated by `runtime_copy`
 * @param env `RuntimeEnv` structure
 */
void runtime_free(RuntimeEnv *env) {
    if (env == NULL) {
        return;
    }
    strlist_free(env);
}