OpenVPN 3 Core Library
Loading...
Searching...
No Matches
netutil.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2024- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12
13// Windows network related utilities
14
15#pragma once
16
17#include <string>
18#include "openvpn/win/reg.hpp"
19
20namespace openvpn::Win {
21
22struct NetApi
23{
30 static std::wstring get_itf_id(const std::string &itf_name)
31 {
32 DWORD err;
33 NET_LUID luid;
34 err = ::ConvertInterfaceAliasToLuid(wstring::from_utf8(itf_name).c_str(), &luid);
35 if (err)
36 return {};
37
38 IID guid;
39 err = ::ConvertInterfaceLuidToGuid(&luid, &guid);
40 if (err)
41 return {};
42
43 PWSTR iid_str;
44 if (::StringFromIID(guid, &iid_str) != S_OK)
45 return {};
46
47 std::wstring iid = iid_str;
48 ::CoTaskMemFree(iid_str);
49 return iid;
50 }
51
59 static bool interface_connected(const std::wstring &iid_str)
60 {
61 GUID iid;
62 MIB_IF_ROW2 itf_row;
63
64 // Get LUID from GUID string
65 if (::IIDFromString(iid_str.c_str(), &iid) != S_OK
66 || ::ConvertInterfaceGuidToLuid(&iid, &itf_row.InterfaceLuid) != NO_ERROR)
67 {
68 return false;
69 }
70
71 // Look up interface status
72 if (::GetIfEntry2(&itf_row) != NO_ERROR)
73 {
74 return false;
75 }
76
77 // Check if interface is connected and up
78 if (itf_row.MediaConnectState != MediaConnectStateConnected
79 || itf_row.OperStatus != IfOperStatusUp)
80 {
81 return false;
82 }
83
84 return true;
85 }
86};
87
97template <typename REG = Win::Reg>
98static std::wstring interface_dns_domain(const std::wstring &itf_guid)
99{
100 typename REG::Key itf_key(std::wstring(REG::subkey_ipv4_itfs) + L"\\" + itf_guid);
101
102 auto [domain, error] = REG::get_string(itf_key, L"DhcpDomain");
103 if (!error && !domain.empty())
104 {
105 return domain;
106 }
107 else
108 {
109 auto [domain, error] = REG::get_string(itf_key, L"Domain");
110 if (!error && !domain.empty())
111 {
112 return domain;
113 }
114 }
115
116 return {};
117}
118
127template <typename REG = Win::Reg>
128static bool dhcp_enabled_on_itf(typename REG::Key &itf_key)
129{
130 auto [dhcp, error] = REG::get_dword(itf_key, L"EnableDHCP");
131 return !error && dhcp ? true : false;
132}
133
134} // namespace openvpn::Win
static std::wstring interface_dns_domain(const std::wstring &itf_guid)
Read interface specific domain suffix.
Definition netutil.hpp:98
static bool dhcp_enabled_on_itf(typename REG::Key &itf_key)
Checks if DHCP is enabled for an interface.
Definition netutil.hpp:128
static bool interface_connected(const std::wstring &iid_str)
Check if an interface is connected and up.
Definition netutil.hpp:59
static std::wstring get_itf_id(const std::string &itf_name)
Definition netutil.hpp:30