aboutsummaryrefslogtreecommitdiff
path: root/src/protocols/geminiclient.cpp
blob: 6986250b5c952f1d0f471b2c760c9b0b17f9e223 (plain) (blame)
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
#include "geminiclient.hpp"
#include <cassert>
#include <QDebug>
#include <QSslConfiguration>
#include "kristall.hpp"

GeminiClient::GeminiClient() : ProtocolHandler(nullptr)
{
    connect(&socket, &QSslSocket::encrypted, this, &GeminiClient::socketEncrypted);
    connect(&socket, &QSslSocket::readyRead, this, &GeminiClient::socketReadyRead);
    connect(&socket, &QSslSocket::disconnected, this, &GeminiClient::socketDisconnected);
//    connect(&socket, &QSslSocket::stateChanged, [](QSslSocket::SocketState state) {
//        qDebug() << "Socket state changed to " << state;
//    });
    connect(&socket, QOverload<const QList<QSslError> &>::of(&QSslSocket::sslErrors), this, &GeminiClient::sslErrors);

#if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
    connect(&socket, &QTcpSocket::errorOccurred, this, &GeminiClient::socketError);
#else
    connect(&socket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error), this, &GeminiClient::socketError);
#endif
}

GeminiClient::~GeminiClient()
{
    is_receiving_body = false;
}

bool GeminiClient::supportsScheme(const QString &scheme) const
{
    return (scheme == "gemini");
}

bool GeminiClient::startRequest(const QUrl &url, RequestOptions options)
{
    if(url.scheme() != "gemini")
        return false;

    // qDebug() << "start request" << url;

    if(socket.state() != QTcpSocket::UnconnectedState) {
        socket.disconnectFromHost();
        socket.close();
        if(not socket.waitForDisconnected(1500))
            return false;
    }

    this->is_error_state = false;

    this->options = options;

    QSslConfiguration ssl_config = socket.sslConfiguration();
    ssl_config.setProtocol(QSsl::TlsV1_2);
    if(not global_gemini_trust.enable_ca)
        ssl_config.setCaCertificates(QList<QSslCertificate> { });
    else
        ssl_config.setCaCertificates(QSslConfiguration::systemCaCertificates());
    socket.setSslConfiguration(ssl_config);

    socket.connectToHostEncrypted(url.host(), url.port(1965));

    this->buffer.clear();
    this->body.clear();
    this->is_receiving_body = false;
    this->suppress_socket_tls_error = true;

    if(not socket.isOpen())
        return false;

    target_url = url;
    mime_type = "<invalid>";

    return true;
}

bool GeminiClient::isInProgress() const
{
    return (socket.state() != QTcpSocket::UnconnectedState);
}

bool GeminiClient::cancelRequest()
{
    // qDebug() << "cancel request" << isInProgress();
    if(isInProgress())
    {
        this->is_receiving_body = false;
        this->socket.disconnectFromHost();
        this->buffer.clear();
        this->body.clear();
        this->socket.waitForDisconnected(500);
        this->socket.close();
        bool success = not isInProgress();
        // qDebug() << "cancel success" << success;
        return success;
    }
    else
    {
        return true;
    }
}

bool GeminiClient::enableClientCertificate(const CryptoIdentity &ident)
{
    this->socket.setLocalCertificate(ident.certificate);
    this->socket.setPrivateKey(ident.private_key);
    return true;
}

void GeminiClient::disableClientCertificate()
{
    this->socket.setLocalCertificate(QSslCertificate{});
    this->socket.setPrivateKey(QSslKey { });
}

void GeminiClient::socketEncrypted()
{
    emit this->hostCertificateLoaded(this->socket.peerCertificate());

    QString request = target_url.toString(QUrl::FormattingOptions(QUrl::FullyEncoded)) + "\r\n";

    QByteArray request_bytes = request.toUtf8();

    qint64 offset = 0;
    while(offset < request_bytes.size()) {
        auto const len = socket.write(request_bytes.constData() + offset, request_bytes.size() - offset);
        if(len <= 0)
        {
            socket.close();
            return;
        }
        offset += len;
    }
}

void GeminiClient::socketReadyRead()
{
    if(this->is_error_state) // don't do any further
        return;
    QByteArray response = socket.readAll();

    if(is_receiving_body)
    {
        body.append(response);
        emit this->requestProgress(body.size());
    }
    else
    {
        for(int i = 0; i < response.size(); i++)
        {
            if(response[i] == '\n') {
                buffer.append(response.data(), i);
                body.append(response.data() + i + 1, response.size() - i - 1);

                // "XY " <META> <CR> <LF>
                if(buffer.size() <= 5) {
                    socket.close();
                    qDebug() << buffer;
                    emit networkError(ProtocolViolation, "Line is too short for valid protocol");
                    return;
                }
                if(buffer.size() >= 1200)
                {
                    emit networkError(ProtocolViolation, "response too large!");
                    socket.close();
                }
                if(buffer[buffer.size() - 1] != '\r') {
                    socket.close();
                    qDebug() << buffer;
                    emit networkError(ProtocolViolation, "Line does not end with <CR> <LF>");
                    return;
                }
                if(not isdigit(buffer[0])) {
                    socket.close();
                    qDebug() << buffer;
                    emit networkError(ProtocolViolation, "First character is not a digit.");
                    return;
                }
                if(not isdigit(buffer[1])) {
                    socket.close();
                    qDebug() << buffer;
                    emit networkError(ProtocolViolation, "Second character is not a digit.");
                    return;
                }
                // TODO: Implement stricter version
                // if(buffer[2] != ' ') {
                if(not isspace(buffer[2])) {
                    socket.close();
                    qDebug() << buffer;
                    emit networkError(ProtocolViolation, "Third character is not a space.");
                    return;
                }

                QString meta = QString::fromUtf8(buffer.data() + 3, buffer.size() - 4);

                int primary_code = buffer[0] - '0';
                int secondary_code = buffer[1] - '0';

                qDebug() << primary_code << secondary_code << meta;

                // We don't need to receive any data after that.
                if(primary_code != 2)
                    socket.close();

                switch(primary_code)
                {
                case 1: // requesting input
                    emit inputRequired(meta);
                    return;

                case 2: // success
                    is_receiving_body = true;
                    mime_type = meta;
                    return;

                case 3: { // redirect
                    QUrl new_url(meta);
                    if(new_url.isValid()) {
                        if(new_url.isRelative())
                            new_url =  target_url.resolved(new_url);
                        assert(not new_url.isRelative());

                        emit redirected(new_url, (secondary_code == 1));
                    }
                    else {
                        emit networkError(ProtocolViolation, "Invalid URL for redirection!");
                    }
                    return;
                }

                case 4: { // temporary failure
                    NetworkError type = UnknownError;
                    switch(secondary_code)
                    {
                    case 1: type = InternalServerError; break;
                    case 2: type = InternalServerError; break;
                    case 3: type = InternalServerError; break;
                    case 4: type = UnknownError; break;
                    }
                    emit networkError(type, meta);
                    return;
                }

                case 5: { // permanent failure
                    NetworkError type = UnknownError;
                    switch(secondary_code)
                    {
                    case 1: type = ResourceNotFound; break;
                    case 2: type = ResourceNotFound; break;
                    case 3: type = ProxyRequest; break;
                    case 9: type = BadRequest; break;
                    }
                    emit networkError(type, meta);
                    return;
                }

                case 6: // client certificate required
                    switch(secondary_code)
                    {
                    case 0:
                        emit certificateRequired(meta);
                        return;

                    case 1:
                        emit networkError(Unauthorized, meta);
                        return;

                    default:
                    case 2:
                        emit networkError(InvalidClientCertificate, meta);
                        return;
                    }
                    return;

                default:
                    emit networkError(ProtocolViolation, "Unspecified status code used!");
                    return;
                }

                assert(false and "unreachable");
            }
        }
        if((buffer.size() + response.size()) >= 1200)
        {
            emit networkError(ProtocolViolation, "META too large!");
            socket.close();
        }
        buffer.append(response);
    }
}

void GeminiClient::socketDisconnected()
{
    if(this->is_receiving_body and not this->is_error_state) {
        body.append(socket.readAll());
        emit requestComplete(body, mime_type);
    }
}

void GeminiClient::sslErrors(QList<QSslError> const & errors)
{
    emit this->hostCertificateLoaded(this->socket.peerCertificate());

    if(options & IgnoreTlsErrors) {
        socket.ignoreSslErrors(errors);
        return;
    }

    QList<QSslError> remaining_errors = errors;
    QList<QSslError> ignored_errors;

    int i = 0;
    while(i < remaining_errors.size())
    {
        auto const & err = remaining_errors.at(i);

        bool ignore = false;
        if(SslTrust::isTrustRelated(err.error()))
        {
            switch(global_gemini_trust.getTrust(target_url, socket.peerCertificate()))
            {
            case SslTrust::Trusted:
                ignore = true;
                break;
            case SslTrust::Untrusted:
                this->is_error_state = true;
                this->suppress_socket_tls_error = true;
                emit this->networkError(UntrustedHost, toFingerprintString(socket.peerCertificate()));
                return;
            case SslTrust::Mistrusted:
                this->is_error_state = true;
                this->suppress_socket_tls_error = true;
                emit this->networkError(MistrustedHost, toFingerprintString(socket.peerCertificate()));
                return;
            }
        }
        else if(err.error() == QSslError::UnableToVerifyFirstCertificate)
        {
            ignore = true;
        }

        if(ignore) {
            ignored_errors.append(err);
            remaining_errors.removeAt(0);
        } else {
            i += 1;
        }
    }

    socket.ignoreSslErrors(ignored_errors);

    qDebug() << "ignoring" << ignored_errors.size() << "out of" << errors.size();

    for(auto const & error : remaining_errors) {
        qWarning() << int(error.error()) << error.errorString();
    }

    if(remaining_errors.size() > 0) {
        emit this->networkError(TlsFailure, remaining_errors.first().errorString());
    }
}

void GeminiClient::socketError(QAbstractSocket::SocketError socketError)
{
    // When remote host closes TLS session, the client closes the socket.
    // This is more sane then erroring out here as it's a perfectly legal
    // state and we know the TLS connection has ended.
    if(socketError == QAbstractSocket::RemoteHostClosedError) {
        socket.close();
    } else {
        this->is_error_state = true;
        if(not this->suppress_socket_tls_error) {
            this->emitNetworkError(socketError, socket.errorString());
        }
    }
}