-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathwebservice.cc
232 lines (194 loc) · 6.35 KB
/
webservice.cc
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
#include "simplomon.hh"
#include <nlohmann/json.hpp>
#include "httplib.h"
#include <mutex>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include "index_html.h"
#include "style_css.h"
#include "logic_js.h"
#include "alpine_min_js.h"
#include "simplomon_ico.h"
using namespace std;
static std::mutex s_lock;
static nlohmann::json s_state;
static nlohmann::json s_checkerstates;
void giveToWebService(const std::set<pair<Checker*, std::string>>& cs,
const std::map<std::string, time_t>& startAlerts)
{
std::lock_guard<mutex> m(s_lock);
s_state = nlohmann::json::object();
auto arr = nlohmann::json::array();
for(const auto& c: cs) {
time_t start = 0;
if(auto iter=startAlerts.find(c.second); iter != startAlerts.end())
start = iter->second;
else {
; //fmt::print("Could not find '{} {}' in {} alerts\n",
// c.first->getCheckerName(), c.second, startAlerts.size());
}
arr.push_back(getAgeDesc(start)+": "+c.second);
}
s_state["alerts"] = arr;
}
static nlohmann::json toJson(const SQLiteWriter::var_t& var)
{
nlohmann::json j;
std::visit([&j](auto&& arg) {
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, nullptr_t>)
return;
else {
j = arg;
}
}, var);
return j;
}
void updateWebService()
{
std::lock_guard<mutex> m(s_lock);
s_checkerstates = nlohmann::json::object();
for(auto &c : g_checkers) {
nlohmann::json cstate;
auto attr = c->d_attributes;
nlohmann::json jattr=nlohmann::json::object(), jresults= nlohmann::json::object(), jreasons = nlohmann::json::object();
for(const auto& a : c->d_attributes)
jattr[a.first] = toJson(a.second);
for(const auto& r: c->d_results) {
for(const auto& res : r.second)
jresults[r.first][res.first] = toJson(res.second);
}
for(const auto& r: c->d_reasons.d_reasons) {
for(const auto& res : r.second)
jreasons[r.first].push_back(res);
}
cstate["attr"] = jattr;
cstate["results"] = jresults;
cstate["reasons"] = jreasons;
s_checkerstates[c->getCheckerName()].push_back(cstate);
}
}
static void webserverThread(std::unique_ptr<httplib::Server> svr, ComboAddress ca)
{
if(svr->listen(ca.toString(), ntohs(ca.sin4.sin_port))) {
cout<<"Error launching server: "<<strerror(errno)<<endl;
exit(EXIT_FAILURE);
}
}
static int B64Decode(const std::string& src, std::string& dst)
{
if (src.empty() ) {
dst.clear();
return 0;
}
int dlen = ( src.length() * 6 + 7 ) / 8 ;
ssize_t olen = 0;
dst.resize(dlen);
BIO *bio, *b64;
bio = BIO_new(BIO_s_mem());
BIO_write(bio, src.c_str(), src.length());
b64 = BIO_new(BIO_f_base64());
bio = BIO_push(b64, bio);
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
olen = BIO_read(b64, &dst.at(0), dlen);
if ((olen == 0 || olen == -1) && BIO_should_retry(bio)) {
BIO_free_all(bio);
throw std::runtime_error("BIO_read failed to read all data from memory buffer");
}
BIO_free_all(bio);
if (olen > 0) {
dst.resize(olen);
return 0;
}
return -1;
}
static std::optional<string> g_webpassword;
static std::optional<string> g_webuser;
static bool checkAuth(const httplib::Request& req, httplib::Response &res)
{
string user;
string password;
string dec;
string::size_type pos;
// Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
string auth = req.get_header_value("Authorization");
if(auth.find("Basic ") != 0)
goto fail;
if(!g_webpassword || g_webpassword->empty())
goto fail;
if(B64Decode(auth.substr(6), dec))
goto fail;
pos = dec.find(':');
if(pos == string::npos)
goto fail;
user = dec.substr(0, pos);
password = dec.substr(pos+1);
if(g_webuser && !g_webuser->empty() && *g_webuser != user) {
fmt::print("User specified '{}' did not match configured user '{}'\n",
user, *g_webuser);
goto fail;
}
if(g_webpassword != password) {
fmt::print("Wrong password");
goto fail;
}
// fmt::print("User '{}', password '{}'\n", user, password);
return true;
fail:;
res.set_header("WWW-Authenticate", "Basic realm=\"Simplomon\"");
res.status = 401;
return false;
// WWW-Authenticate: Basic realm="User Visible Realm"
}
void startWebService(sol::table data)
{
checkLuaTable(data, {"address"}, { "password", "user"});
auto svr = make_unique<httplib::Server>();
sol::optional<string> val = data["password"], val2 = data["user"];
if(val != sol::nullopt)
g_webpassword = *val;
if(val2 != sol::nullopt)
g_webuser = *val2;
svr->set_socket_options([](socket_t sock) {
int yes = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
reinterpret_cast<const void *>(&yes), sizeof(yes));
});
svr->Get("/health", [](const httplib::Request &, httplib::Response &res) {
nlohmann::json j;
j["health"]="ok";
res.set_content(j.dump(), "application/json");
});
svr->Get("/state", [](const auto& req, auto& res) {
if(!checkAuth(req, res))
return;
std::lock_guard<mutex> m(s_lock);
res.set_content(s_state.dump(), "application/json");
});
svr->Get("/checker-states/?", [](const auto& req, auto& res) {
if(!checkAuth(req, res))
return;
std::lock_guard<mutex> m(s_lock);
res.set_content(s_checkerstates.dump(), "application/json");
});
svr->Get("/simplomon.ico", [](const auto& req, auto& res) {
res.set_content(string((const char*)___html_simplomon_ico, ___html_simplomon_ico_len), "image/x-icon");
});
svr->Get("/alpine.min.js", [](const auto& req, auto& res) {
res.set_content(string((const char*)___html_alpine_min_js, ___html_alpine_min_js_len), "application/javascript");
});
svr->Get("/logic.js", [](const auto& req, auto& res) {
res.set_content(string((const char*)___html_logic_js, ___html_logic_js_len), "application/javascript");
});
svr->Get("/style.css", [](const auto& req, auto& res) {
res.set_content(string((const char*)___html_style_css, ___html_style_css_len), "text/css");
});
svr->Get("/", [](const auto& req, auto& res) {
res.set_content(string((const char*)___html_index_html, ___html_index_html_len), "text/html");
});
string addr = data.get_or("address", string("0.0.0.0:8080"));
ComboAddress ca(addr, 8080);
fmt::print("Going to launch webserver on {}\n", ca.toStringWithPort());
std::thread t(webserverThread, std::move(svr), ca);
t.detach();
}