xref: /aosp_15_r20/external/cronet/base/posix/sysctl.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2023 The Chromium Authors
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/posix/sysctl.h"
6 
7 #include <sys/sysctl.h>
8 
9 #include <initializer_list>
10 #include <optional>
11 #include <string>
12 
13 #include "base/check_op.h"
14 #include "base/functional/function_ref.h"
15 #include "base/numerics/safe_conversions.h"
16 #include "build/build_config.h"
17 
18 namespace {
19 
StringSysctlImpl(base::FunctionRef<int (char *,size_t *)> sysctl_func)20 std::optional<std::string> StringSysctlImpl(
21     base::FunctionRef<int(char* /*out*/, size_t* /*out_len*/)> sysctl_func) {
22   size_t buf_len;
23   int result = sysctl_func(nullptr, &buf_len);
24   if (result < 0 || buf_len < 1) {
25     return std::nullopt;
26   }
27 
28   std::string value(buf_len - 1, '\0');
29   result = sysctl_func(&value[0], &buf_len);
30   if (result < 0) {
31     return std::nullopt;
32   }
33   CHECK_LE(buf_len - 1, value.size());
34   CHECK_EQ(value[buf_len - 1], '\0');
35   value.resize(buf_len - 1);
36 
37   return value;
38 }
39 }  // namespace
40 
41 namespace base {
42 
StringSysctl(const std::initializer_list<int> & mib)43 std::optional<std::string> StringSysctl(const std::initializer_list<int>& mib) {
44   return StringSysctlImpl([mib](char* out, size_t* out_len) {
45     return sysctl(const_cast<int*>(std::data(mib)),
46                   checked_cast<unsigned int>(std::size(mib)), out, out_len,
47                   nullptr, 0);
48   });
49 }
50 
51 #if !BUILDFLAG(IS_OPENBSD)
StringSysctlByName(const char * name)52 std::optional<std::string> StringSysctlByName(const char* name) {
53   return StringSysctlImpl([name](char* out, size_t* out_len) {
54     return sysctlbyname(name, out, out_len, nullptr, 0);
55   });
56 }
57 #endif
58 
59 }  // namespace base
60