1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/environment.h"
6
7 #include <stddef.h>
8
9 #include <string_view>
10 #include <vector>
11
12 #include "base/memory/ptr_util.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "util/build_config.h"
16
17 #if defined(OS_WIN)
18 #include <windows.h>
19 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
20 #include <stdlib.h>
21 #endif
22
23 namespace base {
24
25 namespace {
26
27 class EnvironmentImpl : public Environment {
28 public:
GetVar(std::string_view variable_name,std::string * result)29 bool GetVar(std::string_view variable_name, std::string* result) override {
30 if (GetVarImpl(variable_name, result))
31 return true;
32
33 // Some commonly used variable names are uppercase while others
34 // are lowercase, which is inconsistent. Let's try to be helpful
35 // and look for a variable name with the reverse case.
36 // I.e. HTTP_PROXY may be http_proxy for some users/systems.
37 char first_char = variable_name[0];
38 std::string alternate_case_var;
39 if (IsAsciiLower(first_char))
40 alternate_case_var = ToUpperASCII(variable_name);
41 else if (IsAsciiUpper(first_char))
42 alternate_case_var = ToLowerASCII(variable_name);
43 else
44 return false;
45 return GetVarImpl(alternate_case_var, result);
46 }
47
SetVar(std::string_view variable_name,const std::string & new_value)48 bool SetVar(std::string_view variable_name,
49 const std::string& new_value) override {
50 return SetVarImpl(variable_name, new_value);
51 }
52
UnSetVar(std::string_view variable_name)53 bool UnSetVar(std::string_view variable_name) override {
54 return UnSetVarImpl(variable_name);
55 }
56
57 private:
GetVarImpl(std::string_view variable_name,std::string * result)58 bool GetVarImpl(std::string_view variable_name, std::string* result) {
59 #if defined(OS_WIN)
60 DWORD value_length = ::GetEnvironmentVariable(
61 reinterpret_cast<LPCWSTR>(UTF8ToUTF16(variable_name).c_str()), nullptr,
62 0);
63 if (value_length == 0)
64 return false;
65 if (result) {
66 std::unique_ptr<char16_t[]> value(new char16_t[value_length]);
67 ::GetEnvironmentVariable(
68 reinterpret_cast<LPCWSTR>(UTF8ToUTF16(variable_name).c_str()),
69 reinterpret_cast<LPWSTR>(value.get()), value_length);
70 *result = UTF16ToUTF8(value.get());
71 }
72 return true;
73 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
74 const char* env_value = getenv(variable_name.data());
75 if (!env_value)
76 return false;
77 // Note that the variable may be defined but empty.
78 if (result)
79 *result = env_value;
80 return true;
81 #endif
82 }
83
SetVarImpl(std::string_view variable_name,const std::string & new_value)84 bool SetVarImpl(std::string_view variable_name,
85 const std::string& new_value) {
86 #if defined(OS_WIN)
87 // On success, a nonzero value is returned.
88 return !!SetEnvironmentVariable(
89 reinterpret_cast<LPCWSTR>(UTF8ToUTF16(variable_name).c_str()),
90 reinterpret_cast<LPCWSTR>(UTF8ToUTF16(new_value).c_str()));
91 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
92 // On success, zero is returned.
93 return !setenv(variable_name.data(), new_value.c_str(), 1);
94 #endif
95 }
96
UnSetVarImpl(std::string_view variable_name)97 bool UnSetVarImpl(std::string_view variable_name) {
98 #if defined(OS_WIN)
99 // On success, a nonzero value is returned.
100 return !!SetEnvironmentVariable(
101 reinterpret_cast<LPCWSTR>(UTF8ToUTF16(variable_name).c_str()), nullptr);
102 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
103 // On success, zero is returned.
104 return !unsetenv(variable_name.data());
105 #endif
106 }
107 };
108
109 // Parses a null-terminated input string of an environment block. The key is
110 // placed into the given string, and the total length of the line, including
111 // the terminating null, is returned.
ParseEnvLine(const NativeEnvironmentString::value_type * input,NativeEnvironmentString * key)112 size_t ParseEnvLine(const NativeEnvironmentString::value_type* input,
113 NativeEnvironmentString* key) {
114 // Skip to the equals or end of the string, this is the key.
115 size_t cur = 0;
116 while (input[cur] && input[cur] != '=')
117 cur++;
118 *key = NativeEnvironmentString(&input[0], cur);
119
120 // Now just skip to the end of the string.
121 while (input[cur])
122 cur++;
123 return cur + 1;
124 }
125
126 } // namespace
127
128 namespace env_vars {
129
130 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
131 // On Posix systems, this variable contains the location of the user's home
132 // directory. (e.g, /home/username/).
133 const char kHome[] = "HOME";
134 #endif
135
136 } // namespace env_vars
137
138 Environment::~Environment() = default;
139
140 // static
Create()141 std::unique_ptr<Environment> Environment::Create() {
142 return std::make_unique<EnvironmentImpl>();
143 }
144
HasVar(std::string_view variable_name)145 bool Environment::HasVar(std::string_view variable_name) {
146 return GetVar(variable_name, nullptr);
147 }
148
149 #if defined(OS_WIN)
150
AlterEnvironment(const char16_t * env,const EnvironmentMap & changes)151 std::u16string AlterEnvironment(const char16_t* env,
152 const EnvironmentMap& changes) {
153 std::u16string result;
154
155 // First copy all unmodified values to the output.
156 size_t cur_env = 0;
157 std::u16string key;
158 while (env[cur_env]) {
159 const char16_t* line = &env[cur_env];
160 size_t line_length = ParseEnvLine(line, &key);
161
162 // Keep only values not specified in the change vector.
163 EnvironmentMap::const_iterator found_change = changes.find(key);
164 if (found_change == changes.end())
165 result.append(line, line_length);
166
167 cur_env += line_length;
168 }
169
170 // Now append all modified and new values.
171 for (EnvironmentMap::const_iterator i = changes.begin(); i != changes.end();
172 ++i) {
173 if (!i->second.empty()) {
174 result.append(i->first);
175 result.push_back('=');
176 result.append(i->second);
177 result.push_back(0);
178 }
179 }
180
181 // An additional null marks the end of the list. We always need a double-null
182 // in case nothing was added above.
183 if (result.empty())
184 result.push_back(0);
185 result.push_back(0);
186 return result;
187 }
188
189 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
190
AlterEnvironment(const char * const * const env,const EnvironmentMap & changes)191 std::unique_ptr<char* []> AlterEnvironment(const char* const* const env,
192 const EnvironmentMap& changes) {
193 std::string value_storage; // Holds concatenated null-terminated strings.
194 std::vector<size_t> result_indices; // Line indices into value_storage.
195
196 // First build up all of the unchanged environment strings. These are
197 // null-terminated of the form "key=value".
198 std::string key;
199 for (size_t i = 0; env[i]; i++) {
200 size_t line_length = ParseEnvLine(env[i], &key);
201
202 // Keep only values not specified in the change vector.
203 EnvironmentMap::const_iterator found_change = changes.find(key);
204 if (found_change == changes.end()) {
205 result_indices.push_back(value_storage.size());
206 value_storage.append(env[i], line_length);
207 }
208 }
209
210 // Now append all modified and new values.
211 for (EnvironmentMap::const_iterator i = changes.begin(); i != changes.end();
212 ++i) {
213 if (!i->second.empty()) {
214 result_indices.push_back(value_storage.size());
215 value_storage.append(i->first);
216 value_storage.push_back('=');
217 value_storage.append(i->second);
218 value_storage.push_back(0);
219 }
220 }
221
222 size_t pointer_count_required =
223 result_indices.size() + 1 + // Null-terminated array of pointers.
224 (value_storage.size() + sizeof(char*) - 1) / sizeof(char*); // Buffer.
225 std::unique_ptr<char*[]> result(new char*[pointer_count_required]);
226
227 // The string storage goes after the array of pointers.
228 char* storage_data =
229 reinterpret_cast<char*>(&result.get()[result_indices.size() + 1]);
230 if (!value_storage.empty())
231 memcpy(storage_data, value_storage.data(), value_storage.size());
232
233 // Fill array of pointers at the beginning of the result.
234 for (size_t i = 0; i < result_indices.size(); i++)
235 result[i] = &storage_data[result_indices[i]];
236 result[result_indices.size()] = 0; // Null terminator.
237
238 return result;
239 }
240
241 #endif // OS_WIN
242
243 } // namespace base
244