-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.cpp
387 lines (314 loc) · 12.1 KB
/
main.cpp
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
#include <cxxopts/cxxopts.hpp>
#ifdef STUN_BUILD_FLAVOR
#include <Metadata.h>
#else
// We're likely not building with buck. For example, this might be ccls indexing
// the file. Just put some dummy values to avoid errors.
#include <string>
const std::string kVersion = "";
const std::string kGitCommitId = "";
const bool kGitDirtyStatus = false;
#endif
#include <common/Configerator.h>
#include <common/Notebook.h>
#include <common/Util.h>
#include <event/EventLoop.h>
#include <event/Timer.h>
#include <event/Trigger.h>
#include <flutter/Server.h>
#include <networking/IPTables.h>
#include <networking/InterfaceConfig.h>
#include <stats/StatsManager.h>
#include <stun/Client.h>
#include <stun/Server.h>
#include <stun/Types.h>
#include <unistd.h>
#include <iostream>
#include <memory>
#include <regex>
#include <stdexcept>
#include <vector>
using namespace stun;
const int kDefaultServerPort = 2859;
static const std::string serverConfigTemplate = R"(
{
"role": "server",
"secret": "SECRET",
"address_pool": "10.100.0.0/24",
"padding_to": 1000,
"data_pipe_rotate_interval": 60
}
)";
static const std::string clientConfigTemplate = R"(
{
"role": "client",
"server": "SERVER_IP",
"user": "USER",
"secret": "SECRET",
"forward_subnets": [
"0.0.0.0/1",
"128.0.0.0/1"
],
"excluded_subnets": [
],
"accept_dns_pushes": ACCEPT_DNS_PUSHES
}
)";
std::string getConfigPath(cxxopts::ParseResult const& arguments) {
if (arguments.count("config")) {
return arguments["config"].as<std::string>();
}
const char* homeDir = getenv("HOME");
assertTrue(homeDir != NULL, "Cannot get $HOME. You must specify an explicit "
"config path with the -c option.");
return std::string(homeDir) + "/.stunrc";
}
std::string getWizardInput(char const* message,
std::function<bool(std::string const&)> validator) {
auto input = std::string{};
do {
if (!std::cin.good()) {
throw std::runtime_error(
"Configuration wizard not completed. Exiting...");
}
std::cout << message;
std::getline(std::cin, input);
} while (!validator(input));
return input;
}
void generateConfig(std::string path) {
std::string role, serverAddr, user, acceptDNSPushes, secret;
std::cout << "I will help you create a stun config file at " << path << "."
<< std::endl;
// Prompt the user for role
role =
getWizardInput("Is this a client or a server? ", [](auto const& value) {
return value == "server" || value == "client";
});
// Prompt the user for server address and client name if we're a client
if (role == "client") {
serverAddr =
getWizardInput("What is the server's address? ",
[](auto const& value) { return !value.empty(); });
user = getWizardInput(
"What is your assigned user name? (May be left empty for an "
"unauthenticated server) ",
[](auto) { return true; });
acceptDNSPushes = getWizardInput(
"Do you want to automatically apply DNS settings that the "
"server sends if available? (yes or no) ",
[](auto const& value) { return (value == "yes") || (value == "no"); });
}
// Prompt the user for the secret
secret = getWizardInput("What is the secret (passcode) for the server? ",
[](auto const& value) { return !value.empty(); });
std::string content =
(role == "server" ? serverConfigTemplate : clientConfigTemplate);
content = std::regex_replace(content, std::regex("SERVER_IP"), serverAddr);
content = std::regex_replace(content, std::regex("ACCEPT_DNS_PUSHES"),
acceptDNSPushes == "yes" ? "true" : "false");
content = std::regex_replace(content, std::regex("SECRET"), secret);
content = std::regex_replace(content, std::regex("USER"), user);
std::ofstream config(path);
config.write(content.c_str(), content.length());
}
cxxopts::ParseResult setupAndParseOptions(int argc, char* argv[]) {
cxxopts::Options options("stun", "A simple layer-3 network packet tunnel.");
options.add_option("", "c", "config",
"Path to the config file. Default is ~/.stunrc.",
cxxopts::value<std::string>(), "");
options.add_option("", "w", "wizard",
"Show config wizard even if a config file exists already.",
cxxopts::value<bool>(), "");
options.add_option("", "f", "flutter",
"Starts a flutter server on given port to export stats.",
cxxopts::value<int>()->implicit_value("4999"), "");
options.add_option(
"", "s", "stats",
"Enable connection stats logging. You "
"can also give a numeric frequency in "
"milliseconds.",
cxxopts::value<int>()->implicit_value("1000")->default_value("1000"), "");
options.add_option("", "v", "verbose", "Log more verbosely.",
cxxopts::value<bool>(), "");
options.add_option("", "", "very-verbose", "Log very verbosely.",
cxxopts::value<bool>(), "");
options.add_option("", "h", "help", "Print help and usage info.",
cxxopts::value<bool>(), "");
auto arguments = [&options, &argc, &argv]() {
try {
return options.parse(argc, argv);
} catch (cxxopts::OptionException const& ex) {
std::cout << "Cannot parse options: " << ex.what() << std::endl;
std::cout << std::endl << options.help() << std::endl;
exit(1);
}
}();
if (arguments.count("help")) {
std::cout << options.help() << std::endl;
exit(1);
}
if (arguments.count("very-verbose")) {
common::Logger::getDefault("").setLoggingThreshold(
common::LogLevel::VERY_VERBOSE);
} else if (arguments.count("verbose")) {
common::Logger::getDefault("").setLoggingThreshold(
common::LogLevel::VERBOSE);
} else {
common::Logger::getDefault("").setLoggingThreshold(common::LogLevel::INFO);
}
return arguments;
}
auto parseSubnets(std::string const& key) {
if (!common::Configerator::hasKey(key)) {
return std::vector<SubnetAddress>{};
}
auto subnets = common::Configerator::getStringArray(key);
auto results = std::vector<SubnetAddress>{};
for (auto const& subnet : subnets) {
results.push_back(SubnetAddress(subnet));
}
return results;
}
auto parseStaticHosts() -> std::map<std::string, IPAddress> {
auto staticHostsConfig = common::Configerator::getJSON()["static_hosts"];
auto result = std::map<std::string, IPAddress>{};
if (!staticHostsConfig.is_null()) {
result = staticHostsConfig.get<std::map<std::string, IPAddress>>();
}
return result;
}
std::map<std::string, size_t> parseQuotaTable() {
auto raw =
common::Configerator::get<std::map<std::string, size_t>>("quotas", {});
for (auto it = raw.begin(); it != raw.end(); it++) {
it->second *= 1024 * 1024 * 1024 /* GB -> Bytes */;
}
return raw;
}
std::unique_ptr<stun::Server> setupServer(event::EventLoop& loop,
std::string getServerConfigID) {
auto config = Server::Config{
getServerConfigID,
common::Configerator::get<int>("port", kDefaultServerPort),
networking::SubnetAddress{
common::Configerator::get<std::string>("address_pool")},
common::Configerator::get<std::string>("masquerade_output_interface", ""),
common::Configerator::get<bool>("encryption", true),
common::Configerator::get<std::string>("secret", ""),
common::Configerator::get<size_t>("padding_to", 0),
common::Configerator::get<bool>("compression", false),
std::chrono::seconds(
common::Configerator::get<size_t>("data_pipe_rotate_interval", 0)),
common::Configerator::get<bool>("authentication", false),
common::Configerator::get<size_t>("mtu",
networking::kTunnelEthernetDefaultMTU),
parseQuotaTable(),
parseStaticHosts(),
common::Configerator::get<std::vector<networking::IPAddress>>(
"dns_pushes", {}),
};
return std::make_unique<stun::Server>(loop, config);
}
auto getDataPipePreference() {
if (!common::Configerator::hasKey("data_pipe_preference")) {
return std::vector<stun::DataPipeType>{stun::DataPipeType::UDP};
}
auto dataPipePreference =
common::Configerator::getJSON()["data_pipe_preference"]
.get<std::vector<stun::DataPipeType>>();
if (dataPipePreference.empty()) {
throw std::runtime_error("Empty array specified for data_pipe_preference");
}
return dataPipePreference;
}
std::unique_ptr<stun::Client> setupClient(event::EventLoop& loop) {
auto config = ClientConfig{
SocketAddress(common::Configerator::getString("server"),
common::Configerator::get<int>("port", kDefaultServerPort)),
getDataPipePreference(),
common::Configerator::get<bool>("encryption", true),
common::Configerator::get<std::string>("secret", ""),
common::Configerator::get<size_t>("padding_to", 0),
std::chrono::seconds(
common::Configerator::get<size_t>("data_pipe_rotate_interval", 0)),
common::Configerator::get<std::string>("user", ""),
common::Configerator::get<size_t>("mtu",
networking::kTunnelEthernetDefaultMTU),
common::Configerator::get<bool>("accept_dns_pushes", false),
parseSubnets("forward_subnets"),
parseSubnets("excluded_subnets"),
parseSubnets("provided_subnets")};
return std::make_unique<stun::Client>(loop, config);
}
std::unique_ptr<flutter::Server>
setupFlutterServer(event::EventLoop& loop,
cxxopts::ParseResult const& arguments) {
if (arguments.count("flutter") == 0) {
return nullptr;
}
auto port = arguments["flutter"].as<int>();
auto flutterServerConfig = flutter::ServerConfig{port};
return std::make_unique<flutter::Server>(loop, flutterServerConfig);
}
std::string getServerConfigID(std::string const& configPath) {
unsigned long hash = 5381;
for (size_t i = 0; i < configPath.length(); i++) {
hash = ((hash << 5) + hash) + configPath[i];
}
return std::to_string(hash);
}
std::string generateNotebookPath(std::string const& configPath) {
return "/tmp/stun-notebook-" + getServerConfigID(configPath);
}
int main(int argc, char* argv[]) {
event::EventLoop loop;
#define XSTRINGIFY(str) #str
#define STRINGIFY(str) XSTRINGIFY(str)
auto buildFlavor = STRINGIFY(STUN_BUILD_FLAVOR);
#undef STRINGIFY
#undef XSTRINGIFY
auto gitVersion = kGitCommitId;
if (kGitDirtyStatus) {
gitVersion += " dirty";
}
auto version = kVersion + " (" + buildFlavor + " build, " + gitVersion + ")";
LOG_I("Main") << "Running version " << version << std::endl;
auto arguments = setupAndParseOptions(argc, argv);
std::string configPath = getConfigPath(arguments);
if (arguments.count("wizard") || access(configPath.c_str(), F_OK) == -1) {
generateConfig(configPath);
}
common::Configerator config(configPath);
common::Notebook notebook(generateNotebookPath(configPath));
LOG_V("Main") << "Config path is: " << configPath << std::endl;
LOG_V("Main") << "Notebook path is: " << generateNotebookPath(configPath)
<< std::endl;
std::unique_ptr<event::Timer> statsTimer;
std::unique_ptr<event::Action> statsDumper;
// Sets up stats collection
event::Duration statsDumpInerval =
std::chrono::milliseconds(arguments["stats"].as<int>());
statsTimer = loop.createTimer(statsDumpInerval);
statsDumper =
loop.createAction("main()::statsDumper", {statsTimer->didFire()});
statsDumper->callback = [&statsTimer, statsDumpInerval]() {
stats::StatsManager::collect();
statsTimer->extend(statsDumpInerval);
};
stats::StatsManager::subscribe([](auto const& data) {
stats::StatsManager::dump(LOG_V("Stats"), data);
});
auto flutterServer = setupFlutterServer(loop, arguments);
std::string role = common::Configerator::getString("role");
LOG_I("Main") << "Running as " << role << std::endl;
std::unique_ptr<stun::Server> server;
std::unique_ptr<stun::Client> client;
if (role == "server") {
server = setupServer(loop, getServerConfigID(configPath));
} else {
client = setupClient(loop);
}
loop.run();
return 0;
}