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 <vector>
10
11 #include "base/memory/ptr_util.h"
12 #include "base/strings/string_piece.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "build/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(StringPiece variable_name,std::string * result)29 bool GetVar(StringPiece 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(StringPiece variable_name,const std::string & new_value)48 bool SetVar(StringPiece variable_name,
49 const std::string& new_value) override {
50 return SetVarImpl(variable_name, new_value);
51 }
52
UnSetVar(StringPiece variable_name)53 bool UnSetVar(StringPiece variable_name) override {
54 return UnSetVarImpl(variable_name);
55 }
56
57 private:
GetVarImpl(StringPiece variable_name,std::string * result)58 bool GetVarImpl(StringPiece variable_name, std::string* result) {
59 #if defined(OS_WIN)
60 DWORD value_length =
61 ::GetEnvironmentVariable(UTF8ToWide(variable_name).c_str(), nullptr, 0);
62 if (value_length == 0)
63 return false;
64 if (result) {
65 std::unique_ptr<wchar_t[]> value(new wchar_t[value_length]);
66 ::GetEnvironmentVariable(UTF8ToWide(variable_name).c_str(), value.get(),
67 value_length);
68 *result = WideToUTF8(value.get());
69 }
70 return true;
71 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
72 const char* env_value = getenv(variable_name.data());
73 if (!env_value)
74 return false;
75 // Note that the variable may be defined but empty.
76 if (result)
77 *result = env_value;
78 return true;
79 #endif
80 }
81
SetVarImpl(StringPiece variable_name,const std::string & new_value)82 bool SetVarImpl(StringPiece variable_name, const std::string& new_value) {
83 #if defined(OS_WIN)
84 // On success, a nonzero value is returned.
85 return !!SetEnvironmentVariable(UTF8ToWide(variable_name).c_str(),
86 UTF8ToWide(new_value).c_str());
87 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
88 // On success, zero is returned.
89 return !setenv(variable_name.data(), new_value.c_str(), 1);
90 #endif
91 }
92
UnSetVarImpl(StringPiece variable_name)93 bool UnSetVarImpl(StringPiece variable_name) {
94 #if defined(OS_WIN)
95 // On success, a nonzero value is returned.
96 return !!SetEnvironmentVariable(UTF8ToWide(variable_name).c_str(), nullptr);
97 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
98 // On success, zero is returned.
99 return !unsetenv(variable_name.data());
100 #endif
101 }
102 };
103
104 // Parses a null-terminated input string of an environment block. The key is
105 // placed into the given string, and the total length of the line, including
106 // the terminating null, is returned.
ParseEnvLine(const NativeEnvironmentString::value_type * input,NativeEnvironmentString * key)107 size_t ParseEnvLine(const NativeEnvironmentString::value_type* input,
108 NativeEnvironmentString* key) {
109 // Skip to the equals or end of the string, this is the key.
110 size_t cur = 0;
111 while (input[cur] && input[cur] != '=')
112 cur++;
113 *key = NativeEnvironmentString(&input[0], cur);
114
115 // Now just skip to the end of the string.
116 while (input[cur])
117 cur++;
118 return cur + 1;
119 }
120
121 } // namespace
122
123 namespace env_vars {
124
125 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
126 // On Posix systems, this variable contains the location of the user's home
127 // directory. (e.g, /home/username/).
128 const char kHome[] = "HOME";
129 #endif
130
131 } // namespace env_vars
132
133 Environment::~Environment() = default;
134
135 // static
Create()136 std::unique_ptr<Environment> Environment::Create() {
137 return std::make_unique<EnvironmentImpl>();
138 }
139
HasVar(StringPiece variable_name)140 bool Environment::HasVar(StringPiece variable_name) {
141 return GetVar(variable_name, nullptr);
142 }
143
144 #if defined(OS_WIN)
145
AlterEnvironment(const wchar_t * env,const EnvironmentMap & changes)146 string16 AlterEnvironment(const wchar_t* env,
147 const EnvironmentMap& changes) {
148 string16 result;
149
150 // First copy all unmodified values to the output.
151 size_t cur_env = 0;
152 string16 key;
153 while (env[cur_env]) {
154 const wchar_t* line = &env[cur_env];
155 size_t line_length = ParseEnvLine(line, &key);
156
157 // Keep only values not specified in the change vector.
158 EnvironmentMap::const_iterator found_change = changes.find(key);
159 if (found_change == changes.end())
160 result.append(line, line_length);
161
162 cur_env += line_length;
163 }
164
165 // Now append all modified and new values.
166 for (EnvironmentMap::const_iterator i = changes.begin();
167 i != changes.end(); ++i) {
168 if (!i->second.empty()) {
169 result.append(i->first);
170 result.push_back('=');
171 result.append(i->second);
172 result.push_back(0);
173 }
174 }
175
176 // An additional null marks the end of the list. We always need a double-null
177 // in case nothing was added above.
178 if (result.empty())
179 result.push_back(0);
180 result.push_back(0);
181 return result;
182 }
183
184 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
185
AlterEnvironment(const char * const * const env,const EnvironmentMap & changes)186 std::unique_ptr<char* []> AlterEnvironment(const char* const* const env,
187 const EnvironmentMap& changes) {
188 std::string value_storage; // Holds concatenated null-terminated strings.
189 std::vector<size_t> result_indices; // Line indices into value_storage.
190
191 // First build up all of the unchanged environment strings. These are
192 // null-terminated of the form "key=value".
193 std::string key;
194 for (size_t i = 0; env[i]; i++) {
195 size_t line_length = ParseEnvLine(env[i], &key);
196
197 // Keep only values not specified in the change vector.
198 EnvironmentMap::const_iterator found_change = changes.find(key);
199 if (found_change == changes.end()) {
200 result_indices.push_back(value_storage.size());
201 value_storage.append(env[i], line_length);
202 }
203 }
204
205 // Now append all modified and new values.
206 for (EnvironmentMap::const_iterator i = changes.begin();
207 i != changes.end(); ++i) {
208 if (!i->second.empty()) {
209 result_indices.push_back(value_storage.size());
210 value_storage.append(i->first);
211 value_storage.push_back('=');
212 value_storage.append(i->second);
213 value_storage.push_back(0);
214 }
215 }
216
217 size_t pointer_count_required =
218 result_indices.size() + 1 + // Null-terminated array of pointers.
219 (value_storage.size() + sizeof(char*) - 1) / sizeof(char*); // Buffer.
220 std::unique_ptr<char* []> result(new char*[pointer_count_required]);
221
222 // The string storage goes after the array of pointers.
223 char* storage_data = reinterpret_cast<char*>(
224 &result.get()[result_indices.size() + 1]);
225 if (!value_storage.empty())
226 memcpy(storage_data, value_storage.data(), value_storage.size());
227
228 // Fill array of pointers at the beginning of the result.
229 for (size_t i = 0; i < result_indices.size(); i++)
230 result[i] = &storage_data[result_indices[i]];
231 result[result_indices.size()] = 0; // Null terminator.
232
233 return result;
234 }
235
236 #endif // OS_WIN
237
238 } // namespace base
239