File: sysinfo.cpp

package info (click to toggle)
openvpn3-client 24.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 19,384 kB
  • sloc: cpp: 180,128; python: 11,591; ansic: 1,878; sh: 1,767; java: 402; lisp: 81; makefile: 44
file content (87 lines) | stat: -rw-r--r-- 2,208 bytes parent folder | download | duplicates (2)
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
//  OpenVPN 3 Linux client -- Next generation OpenVPN client
//
//  SPDX-License-Identifier: AGPL-3.0-only
//
//  Copyright (C) 2017-  OpenVPN Inc <sales@openvpn.net>
//  Copyright (C) 2024-  Răzvan Cojocaru <razvan.cojocaru@openvpn.com>
//

#include "sysinfo.hpp"
#include <chrono>
#include <cstring>
#include <ctime>
#include <errno.h>
#include <fstream>
#include <iomanip>
#include <regex>
#include <sstream>
#include <streambuf>
#include <stdexcept>
#include <sys/utsname.h>

namespace {

std::string search_os_release(const std::string &key, const std::string &contents)
{
    const std::regex REG{R"-((^|\n))-" + key + R"-(\s*=\s*"?([^"^\n]*)"?)-"};
    std::smatch m;

    if (std::regex_search(contents, m, REG))
        return m[2];

    return {};
}

} // end of anonymous namespace

namespace DevPosture {

SysInfo::SysInfo()
{
    using namespace std::string_literals;

    utsname un{};

    if (::uname(&un))
        throw std::runtime_error("Failed to retrieve OS information: "s + strerror(errno));

    uname = {un.sysname, un.machine, un.version, un.release};
    os_release.extra_version = un.release;

    std::ifstream oi("/etc/os-release");

    // It's fine, we have uname() fallbacks.
    if (!oi)
        return;

    const std::string contents((std::istreambuf_iterator<char>(oi)),
                               std::istreambuf_iterator<char>());

    os_release.version_id = search_os_release("VERSION_ID", contents);
    os_release.id = search_os_release("ID", contents);
    os_release.cpe = search_os_release("CPE_NAME", contents);

    std::string tentative_version = search_os_release("VERSION", contents);
    if (!tentative_version.empty())
        os_release.extra_version = tentative_version;
}

DateTime::DateTime()
{
    auto now = std::chrono::system_clock::now();
    auto now_time_t = std::chrono::system_clock::to_time_t(now);

    std::stringstream ss;
    ss << std::put_time(std::localtime(&now_time_t), "%F");
    date = ss.str();

    ss.str("");
    ss << std::put_time(std::localtime(&now_time_t), "%T");
    time = ss.str();

    ss.str("");
    ss << std::put_time(std::localtime(&now_time_t), "%z");
    timezone = ss.str();
}

} // namespace DevPosture