-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathGetEnvironment.cpp
More file actions
595 lines (488 loc) Β· 17.9 KB
/
GetEnvironment.cpp
File metadata and controls
595 lines (488 loc) Β· 17.9 KB
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
// MLB Utility Library Module File
// ////////////////////////////////////////////////////////////////////////////
/*
File Name : %M%
File Version : %I%
Last Extracted : %D% %T%
Last Updated : %E% %U%
File Description : Implementation of logic to retrieve the environment.
Revision History : 1993-10-02 --- Creation
Michael L. Brock
Copyright Michael L. Brock 1993 - 2018.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
// Required include files...
// ////////////////////////////////////////////////////////////////////////////
#include <Utility/GetEnvironment.hpp>
#include <Utility/Utility_Exception.hpp>
#ifndef _Windows
# include <unistd.h>
#endif // #ifdef _Windows
#include <boost/shared_ptr.hpp>
// ////////////////////////////////////////////////////////////////////////////
namespace MLB {
namespace Utility {
// ////////////////////////////////////////////////////////////////////////////
std::string::size_type GetEnvStringSeparatorIndex(const std::string &env_string)
{
std::string::size_type sep_position = env_string.find('=');
if (sep_position == std::string::npos) {
std::ostringstream error_text;
error_text << "The environment string '" << env_string <<
"' does not contain an equals sign.";
ThrowInvalidArgument(error_text);
}
if (sep_position == 0) {
std::ostringstream error_text;
error_text << "The environment string '" << env_string <<
"' does not contain an environment variable name (that is, the "
"equals sign is the first character of the string).";
ThrowInvalidArgument(error_text);
}
return(sep_position);
}
// ////////////////////////////////////////////////////////////////////////////
#ifdef _Windows
namespace {
// ////////////////////////////////////////////////////////////////////////////
std::string GetWinEnvironmentBuffer()
{
std::string env_buffer;
#ifdef UNICODE
boost::shared_ptr<wchar_t> original_ptr(::GetEnvironmentStrings(),
::FreeEnvironmentStrings);
const wchar_t *begin_ptr = original_ptr.get();
const wchar_t *end_ptr = begin_ptr;
while (*end_ptr != L'\0') {
if (*++end_ptr == L'\0')
end_ptr++;
}
int src_length = static_cast<int>(end_ptr - begin_ptr + 1);
int dst_length = ::WideCharToMultiByte(CP_ACP, 0, begin_ptr,
src_length, NULL, 0, NULL, NULL);
if (dst_length < 1) {
std::ostringstream error_text;
error_text << "The wide character string can not be converted: The "
"attempt to determine the ANSI equivalent length returned " <<
dst_length << ".";
ThrowLogicError(error_text.str());
}
std::string(static_cast<std::size_t>(dst_length), '\0').swap(env_buffer);
if (!::WideCharToMultiByte(CP_ACP, 0, begin_ptr, src_length,
const_cast<char *>(env_buffer.c_str()), dst_length, NULL, NULL ))
ThrowLogicError("Attempt to convert a Unicode environment buffer "
"failed.");
#else
boost::shared_ptr<char> original_ptr(::GetEnvironmentStrings(),
::FreeEnvironmentStrings);
const char *begin_ptr = original_ptr.get();
const char *curr_ptr = begin_ptr;
if (begin_ptr) {
while (*curr_ptr)
curr_ptr += ::strlen(curr_ptr) + 1;
std::string(begin_ptr,
static_cast<std::size_t>((curr_ptr - begin_ptr) + 1)).
swap(env_buffer);
}
#endif // #ifdef UNICODE
return(env_buffer);
}
// ////////////////////////////////////////////////////////////////////////////
} // Anonymous namespace
#endif // #ifdef _Windows
// ////////////////////////////////////////////////////////////////////////////
void GetEnvironment(EnvpList &env_list)
{
EnvpList tmp_env_list;
#ifdef _Windows
try {
std::string env_string(GetWinEnvironmentBuffer());
const char *env_strings_ptr = env_string.c_str();
if (env_string.empty())
throw ExceptionGeneral("Unable to get a pointer to the list of "
"environment strings.");
// If returned pointer pointers to ASCII NUL, then no environment.
if (*env_strings_ptr) {
// First few strings returned by GetEnvironmentStrings() are drive
// letter settings which are distinguished by beginning with an
// equals sign ('='). We skip over them...
while (*env_strings_ptr && (*env_strings_ptr == '='))
env_strings_ptr += ::strlen(env_strings_ptr) + 1;
// Now we can extract the environment strings...
while (*env_strings_ptr) {
tmp_env_list.push_back(env_strings_ptr);
env_strings_ptr += ::strlen(env_strings_ptr) + 1;
}
}
}
catch (const std::exception &except) {
Rethrow(except, "Unable to retrieve the Windows environment "
"variables: " + std::string(except.what()));
}
#else
char **env_ptr = environ;
if (env_ptr == NULL)
throw ExceptionGeneral("Unable to get the list of environment strings.");
while (*env_ptr != NULL)
tmp_env_list.push_back(*env_ptr++);
#endif // #ifdef _Windows
env_list.swap(tmp_env_list);
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
EnvpList GetEnvironment()
{
EnvpList env_list;
GetEnvironment(env_list);
return(env_list);
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
void CheckEnvironment(const EnvpList &envp_list)
{
unsigned int count_1 = 0;
EnvpList::const_iterator iter_b(envp_list.begin());
EnvpList::const_iterator iter_e(envp_list.end());
while (iter_b != iter_e) {
try {
GetEnvStringSeparatorIndex(*iter_b);
}
catch (const std::exception &except) {
std::ostringstream error_text;
error_text << "The environment string at index " << count_1 <<
" is invalid: " << except.what();
Rethrow(except, error_text);
}
++iter_b;
++count_1;
}
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
void EnvpListToEnvElementList(const EnvpList &envp_list,
EnvElementList &env_element_list)
{
EnvElementList tmp_env_element_list;
tmp_env_element_list.reserve(envp_list.size());
EnvpList::const_iterator iter_b(envp_list.begin());
EnvpList::const_iterator iter_e(envp_list.end());
while (iter_b != iter_e) {
tmp_env_element_list.push_back(EnvElement(*iter_b));
++iter_b;
}
env_element_list.swap(tmp_env_element_list);
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
EnvElementList EnvpListToEnvElementList(const EnvpList &envp_list)
{
EnvElementList env_element_list;
EnvpListToEnvElementList(envp_list, env_element_list);
return(env_element_list);
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
void EnvElementListToEnvpList(const EnvElementList &env_element_list,
EnvpList &envp_list)
{
EnvpList tmp_envp_list;
tmp_envp_list.reserve(env_element_list.size());
EnvElementList::const_iterator iter_b(env_element_list.begin());
EnvElementList::const_iterator iter_e(env_element_list.end());
while (iter_b != iter_e) {
tmp_envp_list.push_back(iter_b->env_name_ + "=" + iter_b->env_value_);
++iter_b;
}
envp_list.swap(tmp_envp_list);
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
EnvpList EnvElementListToEnvpList(const EnvElementList &env_element_list)
{
EnvpList envp_list;
EnvElementListToEnvpList(env_element_list, envp_list);
return(envp_list);
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
void EnvpListToEnvElementSet(const EnvpList &envp_list,
EnvElementSet &env_element_list)
{
EnvElementSet tmp_env_element_list;
EnvpList::const_iterator iter_b(envp_list.begin());
EnvpList::const_iterator iter_e(envp_list.end());
while (iter_b != iter_e) {
tmp_env_element_list.insert(EnvElement(*iter_b));
++iter_b;
}
env_element_list.swap(tmp_env_element_list);
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
EnvElementSet EnvpListToEnvElementSet(const EnvpList &envp_list)
{
EnvElementSet env_element_list;
EnvpListToEnvElementSet(envp_list, env_element_list);
return(env_element_list);
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
void EnvElementSetToEnvpList(const EnvElementSet &env_element_list,
EnvpList &envp_list)
{
EnvpList tmp_envp_list;
tmp_envp_list.reserve(env_element_list.size());
EnvElementSet::const_iterator iter_b(env_element_list.begin());
EnvElementSet::const_iterator iter_e(env_element_list.end());
while (iter_b != iter_e) {
tmp_envp_list.push_back(iter_b->env_name_ + "=" + iter_b->env_value_);
++iter_b;
}
envp_list.swap(tmp_envp_list);
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
EnvpList EnvElementSetToEnvpList(const EnvElementSet &env_element_list)
{
EnvpList envp_list;
EnvElementSetToEnvpList(env_element_list, envp_list);
return(envp_list);
}
// ////////////////////////////////////////////////////////////////////////////
namespace {
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
// These won't be merged if 'merge_smart_flag' is 'true'...
// ////////////////////////////////////////////////////////////////////////////
const char *EnvMergeExcludeSmartList[] = {
#ifdef _Windows
"ALLUSERSPROFILE",
"APPDATA",
"CLASSPATH",
"CommonProgramFiles",
"COMPUTERNAME",
"ComSpec",
"HOMEDRIVE",
"HOMEPATH",
"LOGONSERVER",
"NUMBER_OF_PROCESSORS",
"OS",
"PATHEXT",
"PROCESSOR_ARCHITECTURE",
"PROCESSOR_IDENTIFIER",
"PROCESSOR_LEVEL",
"PROCESSOR_REVISION",
"ProgramFiles",
"SystemDrive",
"SystemRoot",
"TEMP",
"TMP",
"USERDOMAIN",
"USERNAME",
"USERPROFILE",
"windir"
#else
"HOSTNAME",
"TERM",
"SHELL",
"WINDOWID",
"USER",
"PWD",
"HOME",
"LOGNAME",
"DISPLAY"
#endif // #ifdef _Windows
};
const unsigned int EnvMergeExcludeSmartCount =
sizeof(EnvMergeExcludeSmartList) / sizeof(EnvMergeExcludeSmartList[0]);
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
// These will be intelligently combined if 'merge_path_flag' is 'true'...
// ////////////////////////////////////////////////////////////////////////////
const char *EnvMergeExcludePathList[] = {
#ifdef _Windows
"INCLUDE",
"LIB",
"Os2LibPath",
"Path"
#else
"MANPATH",
"PATH"
#endif // #ifdef _Windows
};
const unsigned int EnvMergeExcludePathCount =
sizeof(EnvMergeExcludePathList) / sizeof(EnvMergeExcludePathList[0]);
// ////////////////////////////////////////////////////////////////////////////
};
// ////////////////////////////////////////////////////////////////////////////
void MergeEnvironment(const EnvpList &base_env, const EnvpList &added_env,
EnvpList &result_env, bool merge_smart_flag, bool merge_path_flag)
{
// CODE NOTE: To be implemented.
if (merge_path_flag)
ThrowInvalidArgument("The 'merge_path_flag' to 'MLB::Utility::"
"MergeEnvironment()' is not yet supported.");
if (!merge_smart_flag) {
EnvElementSet base_set;
EnvpListToEnvElementSet(base_env, base_set);
EnvpList::const_iterator iter_added_b(added_env.begin());
EnvpList::const_iterator iter_added_e(added_env.end());
while (iter_added_b != iter_added_e) {
EnvElement tmp_added(*iter_added_b);
if (base_set.find(tmp_added) == base_set.end())
base_set.insert(tmp_added);
++iter_added_b;
}
EnvElementSetToEnvpList(base_set, result_env);
}
else {
EnvElementSet added_set;
EnvpListToEnvElementSet(added_env, added_set);
unsigned int count_1;
if (!merge_path_flag) {
for (count_1 = 0; count_1 < EnvMergeExcludePathCount; ++count_1) {
EnvElementSetIter iter_f(added_set.find(
EnvElement(EnvMergeExcludePathList[count_1], "")));
if (iter_f != added_set.end())
added_set.erase(iter_f);
}
}
for (count_1 = 0; count_1 < EnvMergeExcludeSmartCount; ++count_1) {
EnvElementSetIter iter_f(added_set.find(
EnvElement(EnvMergeExcludeSmartList[count_1], "")));
if (iter_f != added_set.end())
added_set.erase(iter_f);
}
EnvpList tmp_added_env;
EnvElementSetToEnvpList(added_set, tmp_added_env);
MergeEnvironment(base_env, tmp_added_env, result_env, false,
merge_path_flag);
}
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
EnvpList MergeEnvironment(const EnvpList &base_env, const EnvpList &added_env,
bool merge_smart_flag, bool merge_path_flag)
{
EnvpList envp_list;
MergeEnvironment(base_env, added_env, envp_list, merge_smart_flag,
merge_path_flag);
return(envp_list);
}
// ////////////////////////////////////////////////////////////////////////////
} // namespace Utility
} // namespace MLB
#ifdef TEST_MAIN
#include <Utility/EmitterSep.hpp>
#include <cstdlib>
#include <iterator>
using namespace MLB::Utility;
// ////////////////////////////////////////////////////////////////////////////
const char *TEST_BaseEnvList[] = {
"SomeBaseEnv1=SomeValue1",
"SomeBaseEnv2=SomeValue2",
"path=/Base/Path1:/Base/Path2"
};
const unsigned int TEST_BaseEnvCount =
sizeof(TEST_BaseEnvList) / sizeof(TEST_BaseEnvList[0]);
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
const char *TEST_AddedEnvList[] = {
"SomeAddedEnv1=SomeValue1",
"SomeAddedEnv2=SomeValue2",
"path=/Added/Path1:/Added/Path2"
};
const unsigned int TEST_AddedEnvCount =
sizeof(TEST_AddedEnvList) / sizeof(TEST_AddedEnvList[0]);
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
void TEST_Populate(unsigned int src_count, const char **src_list,
EnvpList &dst_list)
{
unsigned int count_1;
EnvpList tmp_list;
for (count_1 = 0; count_1 < src_count; ++count_1)
tmp_list.push_back(src_list[count_1]);
dst_list.swap(tmp_list);
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
void TEST_RunTest(const EnvpList &base_env, const EnvpList &added_env,
bool merge_smart_flag, bool merge_path_flag)
{
std::cout << std::setfill('=') << std::setw(79) << "" <<
std::setfill(' ') << std::endl;
std::cout << std::setfill('=') << std::setw(79) << "" <<
std::setfill(' ') << std::endl;
std::cout << "Merge Smart Flag: " << AnyToString(merge_smart_flag) <<
std::endl;
std::cout << "Merge Path Flag : " << AnyToString(merge_path_flag) <<
std::endl;
std::cout << std::setfill('-') << std::setw(79) << "" <<
std::setfill(' ') << std::endl;
std::cout << "Base List:" << std::endl;
std::cout << "---- ----:" << std::endl;
std::copy(base_env.begin(), base_env.end(),
std::ostream_iterator<EnvpList::value_type>(std::cout, "\n"));
std::cout << std::setfill('-') << std::setw(79) << "" << std::endl;
std::cout << "Added List:" << std::endl;
std::cout << "----- ----:" << std::endl;
std::copy(added_env.begin(), added_env.end(),
std::ostream_iterator<EnvpList::value_type>(std::cout, "\n"));
std::cout << std::setfill('=') << std::setw(79) << "" <<
std::setfill(' ') << std::endl;
EnvpList result_env;
MergeEnvironment(base_env, added_env, result_env, merge_smart_flag,
merge_path_flag);
std::cout << std::setfill('-') << std::setw(79) << "" <<
std::setfill(' ') << std::endl;
std::cout << "Result List:" << std::endl;
std::cout << "------ ----:" << std::endl;
std::copy(result_env.begin(), result_env.end(),
std::ostream_iterator<EnvpList::value_type>(std::cout, "\n"));
std::cout << std::setfill('=') << std::setw(79) << "" <<
std::setfill(' ') << std::endl;
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
void TEST_DumpEnv()
{
std::cout << EmitterSep('=');
std::cout << "Complete Environment:\n";
std::cout << EmitterSep('-');
EnvpList real_env(GetEnvironment());
std::copy(real_env.begin(), real_env.end(),
std::ostream_iterator<EnvpList::value_type>(std::cout, "\n"));
std::cout << EmitterSep('=') << std::endl;
}
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
int main()
{
int return_code = EXIT_SUCCESS;
try {
EnvpList base_env;
TEST_Populate(TEST_BaseEnvCount, TEST_BaseEnvList, base_env);
EnvpList added_env;
TEST_Populate(TEST_AddedEnvCount, TEST_AddedEnvList, added_env);
TEST_RunTest(base_env, added_env, false, false);
TEST_RunTest(base_env, added_env, true, false);
TEST_DumpEnv();
}
catch (const std::exception &except) {
std::cerr << std::endl << std::endl << "ERROR: " << except.what() <<
std::endl;
return_code = EXIT_FAILURE;
}
return(return_code);
}
// ////////////////////////////////////////////////////////////////////////////
#endif // #ifdef TEST_MAIN