E-MailRelay
genvironment_win32.cpp
Go to the documentation of this file.
1//
2// Copyright (C) 2001-2023 Graeme Walker <graeme_walker@users.sourceforge.net>
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// This program is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with this program. If not, see <http://www.gnu.org/licenses/>.
16// ===
17///
18/// \file genvironment_win32.cpp
19///
20
21#include "gdef.h"
22#include "genvironment.h"
23#include <cstdlib> // _environ
24#include <cstring>
25#include <vector>
26#include <cerrno>
27
28#if ! GCONFIG_HAVE_GETENV_S
29inline errno_t getenv_s( std::size_t * n_out , char * buffer , std::size_t n_in , const char * name )
30{
31 if( n_out == nullptr || name == nullptr || (!buffer&&n_in) )
32 return EINVAL ;
33
34 const char * p = ::getenv( name ) ;
35 if( p == nullptr )
36 {
37 *n_out = 0 ;
38 return 0 ;
39 }
40
41 size_t n = std::strlen( p ) ;
42 *n_out = n + 1U ;
43
44 if( n >= n_in )
45 return ERANGE ;
46
47 if( buffer )
48 {
49 for( ++n ; n ; n-- )
50 *buffer++ = *p++ ;
51 }
52
53 return 0 ;
54}
55#endif
56
57std::string G::Environment::get( const std::string & name , const std::string & default_ )
58{
59 std::size_t n = 0U ;
60 errno_t rc = getenv_s( &n , nullptr , 0U , name.c_str() ) ;
61 if( n == 0U ) // rc will be ERANGE if the environment variable exists
62 return default_ ;
63
64 std::vector<char> buffer( n ) ;
65 rc = getenv_s( &n , &buffer[0] , n , name.c_str() ) ;
66 if( rc != 0 || n == 0U )
67 return default_ ;
68
69 buffer.push_back( '\0' ) ; // just in case
70 return std::string( &buffer[0] ) ;
71}
72
74{
75 return Environment() ;
76}
77
78void G::Environment::put( const std::string & name , const std::string & value )
79{
80 // dont use _putenv_s() here in order to maintain compatibility
81 // with ancient run-times
82 std::string s = name + "=" + value ;
83 char * deliberately_leaky_copy = _strdup( s.c_str() ) ;
84 GDEF_IGNORE_RETURN _putenv( deliberately_leaky_copy ) ;
85}
86
Holds a set of environment variables and also provides static methods to wrap getenv() and putenv().
Definition: genvironment.h:40
static void put(const std::string &name, const std::string &value)
Sets the environment variable value.
static std::string get(const std::string &name, const std::string &default_)
Returns the environment variable value or the given default.
static Environment minimal(bool sbin=false)
Returns a minimal, safe set of environment variables.