1 /*
2 *
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 /* for secure_getenv. */
20 #ifndef _GNU_SOURCE
21 #define _GNU_SOURCE
22 #endif
23
24 #include <grpc/support/port_platform.h>
25
26 #ifdef GPR_LINUX_ENV
27
28 #include "src/core/lib/gpr/env.h"
29
30 #include <dlfcn.h>
31 #include <features.h>
32 #include <stdlib.h>
33 #include <string.h>
34
35 #include <grpc/support/log.h>
36 #include <grpc/support/string_util.h>
37
38 #include "src/core/lib/gpr/string.h"
39 #include "src/core/lib/gpr/useful.h"
40
gpr_getenv_silent(const char * name,char ** dst)41 const char* gpr_getenv_silent(const char* name, char** dst) {
42 const char* insecure_func_used = nullptr;
43 char* result = nullptr;
44 #if defined(GPR_BACKWARDS_COMPATIBILITY_MODE)
45 typedef char* (*getenv_type)(const char*);
46 static getenv_type getenv_func = NULL;
47 /* Check to see which getenv variant is supported (go from most
48 * to least secure) */
49 const char* names[] = {"secure_getenv", "__secure_getenv", "getenv"};
50 for (size_t i = 0; getenv_func == NULL && i < GPR_ARRAY_SIZE(names); i++) {
51 getenv_func = (getenv_type)dlsym(RTLD_DEFAULT, names[i]);
52 if (getenv_func != NULL && strstr(names[i], "secure") == NULL) {
53 insecure_func_used = names[i];
54 }
55 }
56 result = getenv_func(name);
57 #elif __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17)
58 result = secure_getenv(name);
59 #else
60 result = getenv(name);
61 insecure_func_used = "getenv";
62 #endif
63 *dst = result == nullptr ? result : gpr_strdup(result);
64 return insecure_func_used;
65 }
66
gpr_getenv(const char * name)67 char* gpr_getenv(const char* name) {
68 char* result = nullptr;
69 const char* insecure_func_used = gpr_getenv_silent(name, &result);
70 if (insecure_func_used != nullptr) {
71 gpr_log(GPR_DEBUG, "Warning: insecure environment read function '%s' used",
72 insecure_func_used);
73 }
74 return result;
75 }
76
gpr_setenv(const char * name,const char * value)77 void gpr_setenv(const char* name, const char* value) {
78 int res = setenv(name, value, 1);
79 GPR_ASSERT(res == 0);
80 }
81
82 #endif /* GPR_LINUX_ENV */
83