SNode.C
Loading...
Searching...
No Matches
httplowlevelclient.cpp
Go to the documentation of this file.
1/*
2 * SNode.C - A Slim Toolkit for Network Communication
3 * Copyright (C) Volker Christian <me@vchrist.at>
4 * 2020, 2021, 2022, 2023, 2024, 2025
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20/*
21 * MIT License
22 *
23 * Permission is hereby granted, free of charge, to any person obtaining a copy
24 * of this software and associated documentation files (the "Software"), to deal
25 * in the Software without restriction, including without limitation the rights
26 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27 * copies of the Software, and to permit persons to whom the Software is
28 * furnished to do so, subject to the following conditions:
29 *
30 * The above copyright notice and this permission notice shall be included in
31 * all copies or substantial portions of the Software.
32 *
33 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
39 * THE SOFTWARE.
40 */
41
42#include "core/SNodeC.h"
43#include "core/socket/stream/SocketContext.h"
44#include "core/socket/stream/SocketContextFactory.h"
45#include "net/in/stream/legacy/SocketClient.h"
46#include "net/in/stream/tls/SocketClient.h"
47#include "web/http/client/ResponseParser.h"
48
49#ifndef DOXYGEN_SHOULD_SKIP_THIS
50
51#include "log/Logger.h"
52
53#include <cstddef>
54#include <openssl/ssl.h>
55#include <openssl/x509v3.h>
56#include <string>
57
58// IWYU pragma: no_include <openssl/ssl3.h>
59// IWYU pragma: no_include <openssl/x509.h>
60// IWYU pragma: no_include <openssl/types.h>
61// IWYU pragma: no_include <openssl/asn1.h>
62// IWYU pragma: no_include <openssl/obj_mac.h>
63// IWYU pragma: no_include <openssl/crypto.h>
64
65#endif /* DOXYGEN_SHOULD_SKIP_THIS */
66
67namespace apps::http {
68
69 static web::http::client::ResponseParser* getResponseParser(core::socket::stream::SocketContext* socketContext) {
70 web::http::client::ResponseParser* responseParser = new web::http::client::ResponseParser(
71 socketContext,
72 []() {
73 VLOG(1) << "++ OnStarted";
74 },
75 []([[maybe_unused]] web::http::client::Response& res) {
76 VLOG(1) << "++ OnParsed";
77 },
78 [](int status, const std::string& reason) {
79 VLOG(1) << "++ OnError: " + std::to_string(status) + " - " + reason;
80 });
81
82 return responseParser;
83 }
84
85 class SimpleSocketProtocol : public core::socket::stream::SocketContext {
86 public:
87 explicit SimpleSocketProtocol(core::socket::stream::SocketConnection* socketConnection)
88 : core::socket::stream::SocketContext(socketConnection) {
90 }
91
93
94 void onConnected() override {
95 VLOG(1) << "SimpleSocketProtocol connected";
96 }
97 void onDisconnected() override {
98 VLOG(1) << "SimpleSocketProtocol disconnected";
99 }
100
101 bool onSignal([[maybe_unused]] int signum) override {
102 return true;
103 }
104
105 std::size_t onReceivedFromPeer() override {
107 }
108
109 void onWriteError(int errnum) override {
112 }
113
114 void onReadError(int errnum) override {
117 }
118
119 private:
121 };
122
126
128 public:
130
131 private:
132 core::socket::stream::SocketContext* create(core::socket::stream::SocketConnection* socketConnection) override {
133 return new SimpleSocketProtocol(socketConnection);
134 }
135 };
136
139
140} // namespace apps::http
141
142namespace tls {
143
144 using SocketClient = net::in::stream::tls::SocketClient<apps::http::SimpleSocketProtocolFactory>;
145 using SocketAddress = SocketClient::SocketAddress;
146 using SocketConnection = SocketClient::SocketConnection;
147
149 SocketClient tlsClient(
150 "tls",
151 [](SocketConnection* socketConnection) { // onConnect
152 VLOG(1) << "OnConnect";
153
154 VLOG(1) << "\tServer: " << socketConnection->getRemoteAddress().toString();
155 VLOG(1) << "\tClient: " << socketConnection->getLocalAddress().toString();
156
157 /* Enable automatic hostname checks */
158 // X509_VERIFY_PARAM* param = SSL_get0_param(socketConnection->getSSL());
159
160 // X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
161 // if (!X509_VERIFY_PARAM_set1_host(param, "localhost", sizeof("localhost") - 1)) {
162 // // handle error
163 // socketConnection->close();
164 // }
165 },
166 [](SocketConnection* socketConnection) { // onConnected
167 VLOG(1) << "OnConnected";
168
169 X509* server_cert = SSL_get_peer_certificate(socketConnection->getSSL());
170 if (server_cert != nullptr) {
171 const long verifyErr = SSL_get_verify_result(socketConnection->getSSL());
172
173 VLOG(1) << " Server certificate: " + std::string(X509_verify_cert_error_string(verifyErr));
174
175 char* str = X509_NAME_oneline(X509_get_subject_name(server_cert), nullptr, 0);
176 VLOG(1) << " Subject: " + std::string(str);
177 OPENSSL_free(str);
178
179 str = X509_NAME_oneline(X509_get_issuer_name(server_cert), nullptr, 0);
180 VLOG(1) << " Issuer: " + std::string(str);
181 OPENSSL_free(str);
182
183 // We could do all sorts of certificate verification stuff here before deallocating the certificate.
184
185 GENERAL_NAMES* subjectAltNames =
186 static_cast<GENERAL_NAMES*>(X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
187
188 const int32_t altNameCount = sk_GENERAL_NAME_num(subjectAltNames);
189
190 VLOG(1) << "\t Subject alternative name count: " << altNameCount;
191 for (int32_t i = 0; i < altNameCount; ++i) {
192 GENERAL_NAME* generalName = sk_GENERAL_NAME_value(subjectAltNames, i);
193 if (generalName->type == GEN_URI) {
194 const std::string subjectAltName =
195 std::string(reinterpret_cast<const char*>(ASN1_STRING_get0_data(generalName->d.uniformResourceIdentifier)),
196 static_cast<std::size_t>(ASN1_STRING_length(generalName->d.uniformResourceIdentifier)));
197 VLOG(1) << "\t SAN (URI): '" + subjectAltName;
198 } else if (generalName->type == GEN_DNS) {
199 const std::string subjectAltName =
200 std::string(reinterpret_cast<const char*>(ASN1_STRING_get0_data(generalName->d.dNSName)),
201 static_cast<std::size_t>(ASN1_STRING_length(generalName->d.dNSName)));
202 VLOG(1) << "\t SAN (DNS): '" + subjectAltName;
203 } else {
204 VLOG(1) << "\t SAN (Type): '" + std::to_string(generalName->type);
205 }
206 }
207
208 sk_GENERAL_NAME_pop_free(subjectAltNames, GENERAL_NAME_free);
209
210 X509_free(server_cert);
211 } else {
212 VLOG(1) << " Server certificate: no certificate";
213 }
214
215 socketConnection->sendToPeer("GET /index.html HTTP/1.1\r\nConnection: close\r\n\r\n"); // Connection: close\r\n\r\n");
216 },
217 [](SocketConnection* socketConnection) { // onDisconnect
218 VLOG(1) << "OnDisconnect";
219
220 VLOG(1) << "\tServer: " + socketConnection->getRemoteAddress().toString();
221 VLOG(1) << "\tClient: " + socketConnection->getLocalAddress().toString();
222
223 });
224
225 const SocketAddress remoteAddress("localhost", 8088);
226
227 tlsClient.connect(remoteAddress,
228 [instanceName = tlsClient.getConfig().getInstanceName()](
229 const SocketAddress& socketAddress,
230 const core::socket::State& state) { // example.com:81 simulate connnect timeout
231 switch (state) {
232 case core::socket::State::OK:
233 VLOG(1) << instanceName << ": connected to '" << socketAddress.toString() << "'";
234 break;
235 case core::socket::State::DISABLED:
236 VLOG(1) << instanceName << ": disabled";
237 break;
238 case core::socket::State::ERROR:
239 LOG(ERROR) << instanceName << ": " << socketAddress.toString() << ": " << state.what();
240 break;
241 case core::socket::State::FATAL:
242 LOG(FATAL) << instanceName << ": " << socketAddress.toString() << ": " << state.what();
243 break;
244 }
245 });
246 return tlsClient;
247 }
248
249} // namespace tls
250
251namespace legacy {
252
253 using SocketClient = net::in::stream::legacy::SocketClient<apps::http::SimpleSocketProtocolFactory>;
254 using SocketAddress = SocketClient::SocketAddress;
255 using SocketConnection = SocketClient::SocketConnection;
256
258 SocketClient legacyClient(
259 "legacy",
260 [](SocketConnection* socketConnection) { // OnConnect
261 VLOG(1) << "OnConnect";
262
263 VLOG(1) << "\tServer: " << socketConnection->getRemoteAddress().toString();
264 VLOG(1) << "\tClient: " << socketConnection->getLocalAddress().toString();
265 },
266 [](SocketConnection* socketConnection) { // onConnected
267 VLOG(1) << "OnConnected";
268
269 socketConnection->sendToPeer("GET /index.html HTTP/1.1\r\nConnection: close\r\n\r\n"); // Connection: close\r\n\r\n");
270 },
271 [](SocketConnection* socketConnection) { // onDisconnect
272 VLOG(1) << "OnDisconnect";
273
274 VLOG(1) << "\tServer: " << socketConnection->getRemoteAddress().toString();
275 VLOG(1) << "\tClient: " << socketConnection->getLocalAddress().toString();
276 });
277
278 SocketAddress remoteAddress("localhost", 8080);
279
280 remoteAddress.init();
281
282 VLOG(1) << "###############': " << remoteAddress.getCanonName();
283 VLOG(1) << "###############': " << remoteAddress.toString();
284
285 legacyClient.connect(remoteAddress,
286 [instanceName = legacyClient.getConfig().getInstanceName()](
287 const tls::SocketAddress& socketAddress,
288 const core::socket::State& state) { // example.com:81 simulate connnect timeout
289 switch (state) {
290 case core::socket::State::OK:
291 VLOG(1) << instanceName << ": connected to '" << socketAddress.toString() << "'";
292 break;
293 case core::socket::State::DISABLED:
294 VLOG(1) << instanceName << ": disabled";
295 break;
296 case core::socket::State::ERROR:
297 LOG(ERROR) << instanceName << ": " << socketAddress.toString() << ": " << state.what();
298 break;
299 case core::socket::State::FATAL:
300 LOG(FATAL) << instanceName << ": " << socketAddress.toString() << ": " << state.what();
301 break;
302 }
303 });
304
305 return legacyClient;
306 }
307
308} // namespace legacy
309
310int main(int argc, char* argv[]) {
311 core::SNodeC::init(argc, argv);
312
313 {
314 const legacy::SocketAddress legacyRemoteAddress("localhost", 8080);
315
316 const legacy::SocketClient legacyClient = legacy::getLegacyClient();
317
318 legacyClient.connect(legacyRemoteAddress,
319 [instanceName = legacyClient.getConfig().getInstanceName()](
320 const tls::SocketAddress& socketAddress,
321 const core::socket::State& state) { // example.com:81 simulate connnect timeout
322 switch (state) {
323 case core::socket::State::OK:
324 VLOG(1) << instanceName << ": connected to '" << socketAddress.toString() << "'";
325 break;
326 case core::socket::State::DISABLED:
327 VLOG(1) << instanceName << ": disabled";
328 break;
329 case core::socket::State::ERROR:
330 LOG(ERROR) << instanceName << ": " << socketAddress.toString() << ": " << state.what();
331 break;
332 case core::socket::State::FATAL:
333 LOG(FATAL) << instanceName << ": " << socketAddress.toString() << ": " << state.what();
334 break;
335 }
336 });
337
338 const tls::SocketAddress tlsRemoteAddress = tls::SocketAddress("localhost", 8088);
339
340 const tls::SocketClient tlsClient = tls::getClient();
341
342 tlsClient.connect(tlsRemoteAddress,
343 [instanceName = tlsClient.getConfig().getInstanceName()](
344 const tls::SocketAddress& socketAddress,
345 const core::socket::State& state) { // example.com:81 simulate connnect timeout
346 switch (state) {
347 case core::socket::State::OK:
348 VLOG(1) << instanceName << ": connected to '" << socketAddress.toString() << "'";
349 break;
350 case core::socket::State::DISABLED:
351 VLOG(1) << instanceName << ": disabled";
352 break;
353 case core::socket::State::ERROR:
354 LOG(ERROR) << instanceName << ": " << socketAddress.toString() << ": " << state.what();
355 break;
356 case core::socket::State::FATAL:
357 LOG(FATAL) << instanceName << ": " << socketAddress.toString() << ": " << state.what();
358 break;
359 }
360 });
361 }
362
363 return core::SNodeC::start();
364}
core::socket::stream::SocketContext * create(core::socket::stream::SocketConnection *socketConnection) override
web::http::client::ResponseParser * responseParser
SimpleSocketProtocol(core::socket::stream::SocketConnection *socketConnection)
void onReadError(int errnum) override
void onWriteError(int errnum) override
std::size_t onReceivedFromPeer() override
static void init(int argc, char *argv[])
Definition SNodeC.cpp:54
static int start(const utils::Timeval &timeOut={LONG_MAX, 0})
Definition SNodeC.cpp:60
Config & getConfig() const
Definition Socket.hpp:65
static constexpr int DISABLED
Definition State.h:56
static constexpr int ERROR
Definition State.h:57
std::string what() const
Definition State.cpp:114
static constexpr int FATAL
Definition State.h:58
static constexpr int OK
Definition State.h:55
const SocketClient & connect(const SocketAddress &remoteAddress, const std::function< void(const SocketAddress &, core::socket::State)> &onStatus) const
const SocketAddress & getRemoteAddress() const final
const SocketAddress & getLocalAddress() const final
void sendToPeer(const std::string &data)
SocketContext(core::socket::stream::SocketConnection *socketConnection)
void onReadError(int errnum) override
void shutdownWrite(bool forceClose=false)
void onWriteError(int errnum) override
const std::string & getInstanceName() const
SocketAddress(const std::string &ipOrHostname, uint16_t port)
std::string getCanonName() const
std::string toString(bool expanded=true) const override
void init(const Hints &hints={.aiFlags=0,.aiSockType=0,.aiProtocol=0})
std::size_t parse()
Definition Parser.cpp:92
ResponseParser(core::socket::stream::SocketContext *socketContext, const std::function< void()> &onResponseStart, const std::function< void(Response &)> &onResponseParsed, const std::function< void(int, const std::string &)> &onResponseParseError)
int main(int argc, char *argv[])
static web::http::client::ResponseParser * getResponseParser(core::socket::stream::SocketContext *socketContext)
net::in::stream::legacy::SocketClient< apps::http::SimpleSocketProtocolFactory > SocketClient
SocketClient::SocketAddress SocketAddress
SocketClient::SocketConnection SocketConnection
SocketClient getLegacyClient()
net::in::stream::SocketClient< core::socket::stream::legacy::SocketConnector, net::in::stream::legacy::config::ConfigSocketClient, SocketContextFactoryT, Args... > SocketClient
net::in::stream::SocketClient< core::socket::stream::tls::SocketConnector, net::in::stream::tls::config::ConfigSocketClient, SocketContextFactoryT, Args... > SocketClient
net::in::stream::tls::SocketClient< apps::http::SimpleSocketProtocolFactory > SocketClient
SocketClient getClient()
SocketClient::SocketConnection SocketConnection
SocketClient::SocketAddress SocketAddress