aboutsummaryrefslogtreecommitdiffstats
path: root/liblfjail/getenv.cc
blob: c05189c51d4a3553cd445a89bdfe3fe023538989 (plain) (blame)
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
/*
 * This source code is released into the public domain.
 */

#include <cstdint>
#include <vector>

#include <unistd.h>

#include "getenv.hh"

namespace lfjail {

auto getenv(std::string_view varname) -> std::optional<std::string> {
	// Start with a buffer of this size, and double it every iteration.
	constexpr auto bufinc = std::size_t{1024};

	auto cvarname = std::string(varname);
	auto buf = std::vector<char>(bufinc);
	for (;;) {
		auto const ret = ::getenv_r(cvarname.c_str(),
					    buf.data(), buf.size());

		if (ret == 0)
			return {std::string(buf.data())};

		if (ret == -1 && errno == ERANGE) {
			buf.resize(buf.size() * 2);
			continue;
		}

		return {};
	}
}

} // namespace lfjail