-
Notifications
You must be signed in to change notification settings - Fork 404
/
hostlist.hpp
151 lines (130 loc) · 2.96 KB
/
hostlist.hpp
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012- OpenVPN Inc.
//
// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
//
#ifndef OPENVPN_COMMON_HOSTLIST_H
#define OPENVPN_COMMON_HOSTLIST_H
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <openvpn/common/exception.hpp>
#include <openvpn/common/options.hpp>
#include <openvpn/common/hostport.hpp>
#include <openvpn/random/randapi.hpp>
namespace openvpn::HostList {
struct Host
{
Host()
{
}
Host(const std::string &host_arg, const std::string &port_arg)
: host(host_arg),
port(port_arg)
{
}
bool defined() const
{
return !host.empty();
}
void swap(Host &rhs) noexcept
{
host.swap(rhs.host);
port.swap(rhs.port);
}
void reset()
{
host.clear();
port.clear();
}
std::string to_string() const
{
std::ostringstream os;
if (defined())
os << '[' << host << "]:" << port;
else
os << "UNDEF_HOST";
return os.str();
}
std::string host;
std::string port;
};
class List : public std::vector<Host>
{
public:
List()
{
}
List(const OptionList &opt,
const std::string &directive,
const std::string &default_port)
{
auto hl = opt.get_index_ptr(directive);
if (hl)
{
for (auto &i : *hl)
{
const Option &o = opt[i];
o.touch();
add(o.get(1, 256), o.get_default(2, 16, default_port));
}
}
}
void randomize(RandomAPI &rng)
{
std::shuffle(begin(), end(), rng());
}
std::string to_string() const
{
std::ostringstream os;
for (auto &h : *this)
os << h.to_string() << '\n';
return os.str();
}
private:
void add(const std::string &host,
const std::string &port)
{
const std::string title = "host list";
HostPort::validate_host(host, title);
HostPort::validate_port(port, title);
emplace_back(host, port);
}
};
class Iterator
{
public:
Iterator()
{
reset();
}
void reset()
{
index = -1;
}
template <typename HOST>
bool next(const List &list, HOST &host)
{
if (list.size() > 0)
{
if (++index >= list.size())
index = 0;
const Host &h = list[index];
host.host = h.host;
host.port = h.port;
return true;
}
else
return false;
}
private:
int index;
};
} // namespace openvpn::HostList
#endif