Debian Codegraph @

src/librssguard/network-web/gemini/geminiclient.cpp

raw symbols SCIP
1 // For license of this file, see <project-root-folder>/LICENSE.md.
2 //
3 // This file is heavily inspired by https://github.com/ikskuh/kristall.
4
5 #include "network-web/gemini/geminiclient.h"
6
7 #include "definitions/definitions.h"
8
9 #include <cassert>
10
11 #include <QDebug>
12 #include <QRegularExpression>
13 #include <QSslConfiguration>
14 #include <QUrl>
15
16 bool CryptoIdentity::isValid() const {
17 return !certificate.isNull() && !private_key.isNull();
18 }
19
20 bool CryptoIdentity::isHostFiltered(const QUrl& url) const {
21 if (host_filter.isEmpty()) {
22 return false;
23 }
24
25 QString url_text = url.toString(QUrl::FullyEncoded);
26 QRegularExpression pattern(QRegularExpression::wildcardToRegularExpression(host_filter),
27 QRegularExpression::PatternOption::CaseInsensitiveOption);
28
29 return !pattern.match(url_text).hasMatch();
30 }
31
32 bool CryptoIdentity::isAutomaticallyEnabledOn(const QUrl& url) const {
33 if (host_filter.isEmpty()) {
34 return false;
35 }
36
37 if (!auto_enable) {
38 return false;
39 }
40
41 QString url_text = url.toString(QUrl::FullyEncoded);
42 QRegularExpression pattern(QRegularExpression::wildcardToRegularExpression(host_filter),
43 QRegularExpression::PatternOption::CaseInsensitiveOption);
44
45 return pattern.match(url_text).hasMatch();
46 }
47
48 GeminiClient::GeminiClient(QObject* parent) : QObject(parent) {
49 connect(&m_socket, &QSslSocket::encrypted, this, &GeminiClient::socketEncrypted);
50 connect(&m_socket, &QSslSocket::readyRead, this, &GeminiClient::socketReadyRead);
51 connect(&m_socket, &QSslSocket::disconnected, this, &GeminiClient::socketDisconnected);
52 connect(&m_socket, QOverload<const QList<QSslError>&>::of(&QSslSocket::sslErrors), this, &GeminiClient::sslErrors);
53
54 // connect(&socket, &QSslSocket::stateChanged, [](QSslSocket::SocketState state) {
55 // qDebug() << "Socket state changed to " << state;
56 // });
57
58 #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
59 connect(&m_socket, &QTcpSocket::errorOccurred, this, &GeminiClient::socketError);
60 #else
61 connect(&m_socket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error), this, &GeminiClient::socketError);
62 #endif
63
64 // States
65 connect(&m_socket, &QAbstractSocket::hostFound, this, [this]() {
66 emit this->requestStateChange(RequestState::HostFound);
67 });
68
69 connect(&m_socket, &QAbstractSocket::connected, this, [this]() {
70 emit this->requestStateChange(RequestState::Connected);
71 });
72
73 connect(&m_socket, &QAbstractSocket::disconnected, this, [this]() {
74 emit this->requestStateChange(RequestState::None);
75 });
76
77 emit requestStateChange(RequestState::None);
78 }
79
80 GeminiClient::~GeminiClient() {
81 m_isReceivingBody = false;
82 }
83
84 bool GeminiClient::supportsUrl(const QString& url) const {
85 return url.startsWith(QL1S("gemini://"));
86 }
87
88 bool GeminiClient::supportsUrl(const QUrl& url) const {
89 return url.scheme() == QL1S("gemini");
90 }
91
92 bool GeminiClient::startRequest(const QUrl& url, RequestOptions options) {
93 if (!supportsUrl(url)) {
94 return false;
95 }
96
97 // qDebug() << "start request" << url;
98
99 if (m_socket.state() != QTcpSocket::UnconnectedState) {
100 m_socket.disconnectFromHost();
101 m_socket.close();
102
103 if (!m_socket.waitForDisconnected(1500)) {
104 return false;
105 }
106 }
107
108 emit requestStateChange(RequestState::Started);
109
110 m_inErrorState = false;
111 options = options;
112
113 QSslConfiguration ssl_config = m_socket.sslConfiguration();
114 ssl_config.setProtocol(QSsl::TlsV1_2OrLater);
115
116 /*
117 if (not kristall::globals().trust.gemini.enable_ca)
118 ssl_config.setCaCertificates(QList<QSslCertificate>{});
119 else
120 */
121
122 ssl_config.setCaCertificates(QSslConfiguration::systemCaCertificates());
123
124 /*
125 */
126
127 m_socket.setSslConfiguration(ssl_config);
128 m_socket.connectToHostEncrypted(url.host(), url.port(1965));
129
130 m_buffer.clear();
131 m_body.clear();
132 m_isReceivingBody = false;
133 m_suppressSocketTlsErrors = true;
134
135 if (!m_socket.isOpen()) {
136 return false;
137 }
138
139 m_targetUrl = url;
140 m_mimeType = "<invalid>";
141
142 return true;
143 }
144
145 bool GeminiClient::inProgress() const {
146 return m_socket.state() != QTcpSocket::UnconnectedState;
147 }
148
149 bool GeminiClient::cancelRequest() {
150 // qDebug() << "cancel request" << isInProgress();
151 if (inProgress()) {
152 m_isReceivingBody = false;
153 m_socket.disconnectFromHost();
154 m_buffer.clear();
155 m_body.clear();
156
157 if (m_socket.state() != QTcpSocket::UnconnectedState) {
158 m_socket.disconnectFromHost();
159 }
160
161 m_socket.waitForDisconnected(500);
162 m_socket.close();
163
164 bool success = !inProgress();
165
166 // qDebug() << "cancel success" << success;
167
168 return success;
169 }
170 else {
171 return true;
172 }
173 }
174
175 bool GeminiClient::enableClientCertificate(const CryptoIdentity& ident) {
176 m_socket.setLocalCertificate(ident.certificate);
177 m_socket.setPrivateKey(ident.private_key);
178
179 return true;
180 }
181
182 void GeminiClient::disableClientCertificate() {
183 m_socket.setLocalCertificate(QSslCertificate{});
184 m_socket.setPrivateKey(QSslKey{});
185 }
186
187 void GeminiClient::emitNetworkError(QAbstractSocket::SocketError error_code, const QString& textual_description) {
188 NetworkError network_error = UnknownError;
189
190 switch (error_code) {
191 case QAbstractSocket::ConnectionRefusedError:
192 network_error = ConnectionRefused;
193 break;
194
195 case QAbstractSocket::HostNotFoundError:
196 network_error = HostNotFound;
197 break;
198
199 case QAbstractSocket::SocketTimeoutError:
200 network_error = Timeout;
201 break;
202
203 case QAbstractSocket::SslHandshakeFailedError:
204 network_error = TlsFailure;
205 break;
206
207 case QAbstractSocket::SslInternalError:
208 network_error = TlsFailure;
209 break;
210
211 case QAbstractSocket::SslInvalidUserDataError:
212 network_error = TlsFailure;
213 break;
214
215 default:
216 qDebug() << "unhandled network error:" << error_code;
217 break;
218 }
219
220 emit networkError(network_error, textual_description);
221 }
222
223 void GeminiClient::socketEncrypted() {
224 emit hostCertificateLoaded(m_socket.peerCertificate());
225
226 QString request = m_targetUrl.toString(QUrl::FormattingOptions(QUrl::FullyEncoded)) + QSL("\r\n");
227
228 QByteArray request_bytes = request.toUtf8();
229
230 qint64 offset = 0;
231
232 while (offset < request_bytes.size()) {
233 const auto len = m_socket.write(request_bytes.constData() + offset, request_bytes.size() - offset);
234
235 if (len <= 0) {
236 m_socket.close();
237 return;
238 }
239
240 offset += len;
241 }
242 }
243
244 void GeminiClient::socketReadyRead() {
245 if (m_inErrorState) {
246 return;
247 }
248
249 QByteArray response = m_socket.readAll();
250
251 if (m_isReceivingBody) {
252 m_body.append(response);
253
254 emit requestProgress(m_body.size());
255 }
256 else {
257 for (int i = 0; i < response.size(); i++) {
258 if (response[i] == '\n') {
259 m_buffer.append(response.data(), i);
260 m_body.append(response.data() + i + 1, response.size() - i - 1);
261
262 // "XY " <META> <CR> <LF>
263 if (m_buffer.size() < 4) { // we allow an empty <META>
264 m_socket.close();
265
266 qDebug() << m_buffer;
267
268 emit networkError(ProtocolViolation, tr("Line is too short for valid protocol"));
269
270 return;
271 }
272 if (m_buffer.size() >= 1200) {
273 emit networkError(ProtocolViolation, tr("response too large!"));
274
275 m_socket.close();
276 }
277 if (m_buffer[m_buffer.size() - 1] != '\r') {
278 m_socket.close();
279
280 qDebug() << m_buffer;
281
282 emit networkError(ProtocolViolation, tr("Line does not end with <CR> <LF>"));
283
284 return;
285 }
286 if (!std::isdigit(m_buffer[0])) {
287 m_socket.close();
288
289 qDebug() << m_buffer;
290
291 emit networkError(ProtocolViolation, tr("First character is not a digit."));
292
293 return;
294 }
295 if (!std::isdigit(m_buffer[1])) {
296 m_socket.close();
297
298 qDebug() << m_buffer;
299
300 emit networkError(ProtocolViolation, tr("Second character is not a digit."));
301
302 return;
303 }
304
305 // TODO: Implement stricter version
306 // if(buffer[2] != ' ') {
307 if (!std::isspace(m_buffer[2])) {
308 m_socket.close();
309
310 qDebug() << m_buffer;
311
312 emit networkError(ProtocolViolation, tr("Third character is not a space."));
313
314 return;
315 }
316
317 QString meta = QString::fromUtf8(m_buffer.data() + 3, m_buffer.size() - 4);
318
319 int primary_code = m_buffer[0] - '0';
320 int secondary_code = m_buffer[1] - '0';
321
322 qDebug() << primary_code << secondary_code << meta;
323
324 // We don't need to receive any data after that.
325 if (primary_code != 2) {
326 m_socket.close();
327 }
328
329 switch (primary_code) {
330 case 1: // requesting input
331 switch (secondary_code) {
332 case 1:
333 emit inputRequired(meta, true);
334 break;
335
336 case 0:
337 default:
338 emit inputRequired(meta, false);
339 }
340
341 return;
342
343 case 2: // success
344 m_isReceivingBody = true;
345 m_mimeType = meta;
346
347 return;
348
349 case 3: { // redirect
350 QUrl new_url(meta);
351 if (new_url.isValid()) {
352 if (new_url.isRelative()) {
353 new_url = m_targetUrl.resolved(new_url);
354 }
355
356 assert(not new_url.isRelative());
357
358 emit redirected(new_url, (secondary_code == 1));
359 }
360 else {
361 emit networkError(ProtocolViolation, tr("Invalid URL for redirection!"));
362 }
363
364 return;
365 }
366
367 case 4: { // temporary failure
368 NetworkError type = UnknownError;
369
370 switch (secondary_code) {
371 case 1:
372 type = InternalServerError;
373 break;
374
375 case 2:
376 type = InternalServerError;
377 break;
378
379 case 3:
380 type = InternalServerError;
381 break;
382
383 case 4:
384 type = UnknownError;
385 break;
386 }
387
388 emit networkError(type, meta);
389
390 return;
391 }
392
393 case 5: { // permanent failure
394 NetworkError type = UnknownError;
395
396 switch (secondary_code) {
397 case 1:
398 type = ResourceNotFound;
399 break;
400
401 case 2:
402 type = ResourceNotFound;
403 break;
404
405 case 3:
406 type = ProxyRequest;
407 break;
408
409 case 9:
410 type = BadRequest;
411 break;
412 }
413
414 emit networkError(type, meta);
415
416 return;
417 }
418
419 case 6: // client certificate required
420 switch (secondary_code) {
421 case 0:
422 emit certificateRequired(meta);
423 return;
424
425 case 1:
426 emit networkError(Unauthorized, meta);
427 return;
428
429 default:
430 case 2:
431 emit networkError(InvalidClientCertificate, meta);
432 return;
433 }
434
435 return;
436
437 default:
438 emit networkError(ProtocolViolation, tr("Unspecified status code used!"));
439
440 return;
441 }
442
443 assert(false && "unreachable");
444 }
445 }
446 if ((m_buffer.size() + response.size()) >= 1200) {
447 emit networkError(ProtocolViolation, tr("META too large!"));
448
449 m_socket.close();
450 }
451
452 m_buffer.append(response);
453 }
454 }
455
456 void GeminiClient::socketDisconnected() {
457 if (m_isReceivingBody && !m_inErrorState) {
458 m_body.append(m_socket.readAll());
459 emit requestComplete(m_body, m_mimeType);
460 }
461 }
462
463 void GeminiClient::sslErrors(const QList<QSslError>& errors) {
464 emit hostCertificateLoaded(m_socket.peerCertificate());
465
466 if (m_options & IgnoreTlsErrors) {
467 m_socket.ignoreSslErrors(errors);
468 return;
469 }
470
471 QList<QSslError> remaining_errors = errors;
472 QList<QSslError> ignored_errors;
473
474 int i = 0;
475 while (i < remaining_errors.size()) {
476 const auto& err = remaining_errors.at(i);
477
478 bool ignore = false;
479
480 /*
481 */
482 ignore = true;
483 /*
484 if (SslTrust::isTrustRelated(err.error())) {
485 switch (kristall::globals().trust.gemini.getTrust(target_url, socket.peerCertificate())) {
486 case SslTrust::Trusted:
487 ignore = true;
488 break;
489 case SslTrust::Untrusted:
490 this->is_error_state = true;
491 this->suppress_socket_tls_error = true;
492 emit this->networkError(UntrustedHost, toFingerprintString(socket.peerCertificate()));
493 return;
494 case SslTrust::Mistrusted:
495 this->is_error_state = true;
496 this->suppress_socket_tls_error = true;
497 emit this->networkError(MistrustedHost, toFingerprintString(socket.peerCertificate()));
498 return;
499 }
500 }
501
502 else */
503 if (err.error() == QSslError::UnableToVerifyFirstCertificate) {
504 ignore = true;
505 }
506
507 if (ignore) {
508 ignored_errors.append(err);
509 remaining_errors.removeAt(0);
510 }
511 else {
512 i += 1;
513 }
514 }
515
516 m_socket.ignoreSslErrors(ignored_errors);
517
518 qDebug() << "ignoring" << ignored_errors.size() << "out of" << errors.size();
519
520 for (const auto& error : remaining_errors) {
521 qWarning() << int(error.error()) << error.errorString();
522 }
523
524 if (remaining_errors.size() > 0) {
525 emit networkError(TlsFailure, remaining_errors.first().errorString());
526 }
527 }
528
529 void GeminiClient::socketError(QAbstractSocket::SocketError socketError) {
530 // When remote host closes TLS session, the client closes the socket.
531 // This is more sane then erroring out here as it's a perfectly legal
532 // state and we know the TLS connection has ended.
533 if (socketError == QAbstractSocket::RemoteHostClosedError) {
534 m_socket.close();
535 return;
536 }
537
538 m_inErrorState = true;
539
540 if (!m_suppressSocketTlsErrors) {
541 emitNetworkError(socketError, m_socket.errorString());
542 }
543 }
544
545 QUrl GeminiClient::targetUrl() const {
546 return m_targetUrl;
547 }