-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsession.cpp
More file actions
278 lines (211 loc) · 6.19 KB
/
Copy pathsession.cpp
File metadata and controls
278 lines (211 loc) · 6.19 KB
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
/* API session.
*
* Author: Steffen Vogel <post@steffenvogel.de>
* SPDX-FileCopyrightText: 2014-2023 Institute for Automation of Complex Power Systems, RWTH Aachen University
* SPDX-License-Identifier: Apache-2.0
*/
#include <sstream>
#include <libwebsockets.h>
#include <villas/api/request.hpp>
#include <villas/api/response.hpp>
#include <villas/api/session.hpp>
#include <villas/node/memory.hpp>
#include <villas/web.hpp>
using namespace villas;
using namespace villas::node;
using namespace villas::node::api;
Session::Session(lws *w)
: version(Version::VERSION_2), wsi(w), logger(Log::get("api:session")) {
lws_context *ctx = lws_get_context(wsi);
void *user_ctx = lws_context_user(ctx);
web = static_cast<Web *>(user_ctx);
api = web->getApi();
if (!api)
throw RuntimeError("API is disabled");
api->sessions.push_back(this);
logger->debug("Initiated API session: {}", getName());
state = Session::State::ESTABLISHED;
}
Session::~Session() {
api->sessions.remove(this);
logger->debug("Destroyed API session: {}", getName());
}
void Session::execute() {
logger->debug("Running API request: {}", request->toString());
try {
response = std::unique_ptr<Response>(request->execute());
logger->debug("Completed API request: {}", request->toString());
} catch (const Error &e) {
response = std::make_unique<ErrorResponse>(this, e);
logger->warn("API request failed: {}, code={}: {}", request->toString(),
e.code, e.what());
} catch (const RuntimeError &e) {
response = std::make_unique<ErrorResponse>(this, e);
logger->warn("API request failed: {}: {}", request->toString(), e.what());
}
logger->debug(
"Ran pending API requests. Triggering on_writeable callback: wsi={}",
(void *)wsi);
web->callbackOnWritable(wsi);
}
std::string Session::getName() const {
std::stringstream ss;
ss << "version=" << version;
if (wsi) {
char name[128];
char ip[128];
lws_get_peer_addresses(wsi, lws_get_socket_fd(wsi), name, sizeof(name), ip,
sizeof(ip));
ss << ", remote.name=" << name << ", remote.ip=" << ip;
}
return ss.str();
}
void Session::shutdown() {
state = State::SHUTDOWN;
web->callbackOnWritable(wsi);
}
void Session::open(void *in, size_t len) {
int ret;
char buf[32];
auto uri = reinterpret_cast<char *>(in);
try {
unsigned int len;
auto method = getRequestMethod();
if (method == Method::UNKNOWN)
throw RuntimeError("Invalid request method");
ret = lws_hdr_copy(wsi, buf, sizeof(buf), WSI_TOKEN_HTTP_CONTENT_LENGTH);
if (ret < 0)
throw RuntimeError("Failed to get content length");
try {
len = std::stoull(buf);
} catch (const std::invalid_argument &) {
len = 0;
}
request = std::unique_ptr<Request>(
RequestFactory::create(this, uri, method, len));
/* This is an OPTIONS request.
*
* We immediatly send headers and close the connection
* without waiting for a POST body */
if (method == Method::OPTIONS)
lws_callback_on_writable(wsi);
/* This request has no body.
* We can reply immediatly */
else if (len == 0)
api->pending.push(this);
else {
// This request has a HTTP body. We wait for more data to arrive
}
} catch (const Error &e) {
response = std::make_unique<ErrorResponse>(this, e);
lws_callback_on_writable(wsi);
} catch (const RuntimeError &e) {
response = std::make_unique<ErrorResponse>(this, e);
lws_callback_on_writable(wsi);
}
}
void Session::body(void *in, size_t len) {
request->buffer.append((const char *)in, len);
}
void Session::bodyComplete() {
try {
request->decode();
api->pending.push(this);
} catch (const Error &e) {
response = std::make_unique<ErrorResponse>(this, e);
logger->warn("Failed to decode API request: {}", e.what());
}
}
int Session::writeable() {
if (!response)
return 0;
if (!headersSent) {
response->writeHeaders(wsi);
// Now wait, until we can send the body
headersSent = true;
return 0;
} else {
if (response)
return response->writeBody(wsi);
else
return 0;
}
}
int Session::protocolCallback(struct lws *wsi, enum lws_callback_reasons reason,
void *user, void *in, size_t len) {
int ret;
Session *s = reinterpret_cast<Session *>(user);
switch (reason) {
case LWS_CALLBACK_HTTP_BIND_PROTOCOL:
try {
new (s) Session(wsi);
} catch (const RuntimeError &e) {
return -1;
}
break;
case LWS_CALLBACK_HTTP_DROP_PROTOCOL:
if (s == nullptr)
return -1;
s->~Session();
break;
case LWS_CALLBACK_HTTP:
s->open(in, len);
break;
case LWS_CALLBACK_HTTP_BODY:
s->body(in, len);
break;
case LWS_CALLBACK_HTTP_BODY_COMPLETION:
s->bodyComplete();
break;
case LWS_CALLBACK_HTTP_WRITEABLE:
ret = s->writeable();
/*
* HTTP/1.0 no keepalive: close network connection
* HTTP/1.1 or HTTP1.0 + KA: wait / process next transaction
* HTTP/2: stream ended, parent connection remains up
*/
if (ret) {
if (lws_http_transaction_completed(wsi))
return -1;
} else
lws_callback_on_writable(wsi);
break;
default:
break;
}
return 0;
}
Session::Method Session::getRequestMethod() const {
if (lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI))
return Method::GET;
else if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
return Method::POST;
#if defined(LWS_WITH_HTTP_UNCOMMON_HEADERS) || defined(LWS_HTTP_HEADERS_ALL)
else if (lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
return Method::PUT;
else if (lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI))
return Method::PATCH;
else if (lws_hdr_total_length(wsi, WSI_TOKEN_OPTIONS_URI))
return Method::OPTIONS;
#endif
else
return Method::UNKNOWN;
}
std::string Session::methodToString(Method method) {
switch (method) {
case Method::POST:
return "POST";
case Method::GET:
return "GET";
case Method::DELETE:
return "DELETE";
case Method::PUT:
return "PUT";
case Method::PATCH:
return "GPATCHET";
case Method::OPTIONS:
return "OPTIONS";
default:
return "UNKNOWN";
}
}