summaryrefslogtreecommitdiffstats
path: root/src/output/dnssim/connection.c
blob: eeb1ce8a22773dcc4095320cbb05ab0bc2c98b94 (plain)
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/*
 * Copyright (c) 2020, CZ.NIC, z.s.p.o.
 * All rights reserved.
 *
 * This file is part of dnsjit.
 *
 * dnsjit is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * dnsjit is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with dnsjit.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "config.h"

#include "output/dnssim.h"
#include "output/dnssim/internal.h"
#include "output/dnssim/ll.h"
#include "core/assert.h"

#include <string.h>

static core_log_t _log = LOG_T_INIT("output.dnssim");

static bool _conn_is_connecting(_output_dnssim_connection_t* conn)
{
    return (conn->state >= _OUTPUT_DNSSIM_CONN_TCP_HANDSHAKE && conn->state <= _OUTPUT_DNSSIM_CONN_ACTIVE);
}

void _output_dnssim_conn_maybe_free(_output_dnssim_connection_t* conn)
{
    mlassert(conn, "conn can't be nil");
    mlassert(conn->client, "conn must belong to a client");
    if (conn->handle == NULL && conn->handshake_timer == NULL && conn->idle_timer == NULL) {
        _ll_try_remove(conn->client->conn, conn);
        if (conn->tls != NULL) {
            free(conn->tls);
            conn->tls = NULL;
        }
        if (conn->http2 != NULL) {
            free(conn->http2);
            conn->http2 = NULL;
        }
        free(conn);
    }
}

static void _on_handshake_timer_closed(uv_handle_t* handle)
{
    _output_dnssim_connection_t* conn = (_output_dnssim_connection_t*)handle->data;
    mlassert(conn, "conn is nil");
    mlassert(conn->handshake_timer, "conn must have handshake timer when closing it");
    free(conn->handshake_timer);
    conn->handshake_timer = NULL;
    _output_dnssim_conn_maybe_free(conn);
}

static void _on_idle_timer_closed(uv_handle_t* handle)
{
    _output_dnssim_connection_t* conn = (_output_dnssim_connection_t*)handle->data;
    mlassert(conn, "conn is nil");
    mlassert(conn->idle_timer, "conn must have idle timer when closing it");
    free(conn->idle_timer);
    conn->is_idle    = false;
    conn->idle_timer = NULL;
    _output_dnssim_conn_maybe_free(conn);
}

void _output_dnssim_conn_close(_output_dnssim_connection_t* conn)
{
    mlassert(conn, "conn can't be nil");
    mlassert(conn->stats, "conn must have stats");
    mlassert(conn->client, "conn must have client");
    mlassert(conn->client->dnssim, "client must have dnssim");

    output_dnssim_t* self = conn->client->dnssim;

    switch (conn->state) {
    case _OUTPUT_DNSSIM_CONN_CLOSING:
    case _OUTPUT_DNSSIM_CONN_CLOSED:
        return;
    case _OUTPUT_DNSSIM_CONN_TCP_HANDSHAKE:
    case _OUTPUT_DNSSIM_CONN_TLS_HANDSHAKE:
        conn->stats->conn_handshakes_failed++;
        self->stats_sum->conn_handshakes_failed++;
        break;
    case _OUTPUT_DNSSIM_CONN_ACTIVE:
    case _OUTPUT_DNSSIM_CONN_CONGESTED:
        self->stats_current->conn_active--;
        break;
    case _OUTPUT_DNSSIM_CONN_INITIALIZED:
    case _OUTPUT_DNSSIM_CONN_CLOSE_REQUESTED:
        break;
    default:
        lfatal("unknown conn state: %d", conn->state);
    }
    if (conn->prevent_close) {
        lassert(conn->state <= _OUTPUT_DNSSIM_CONN_CLOSE_REQUESTED, "conn already closing");
        conn->state = _OUTPUT_DNSSIM_CONN_CLOSE_REQUESTED;
        return;
    }
    conn->state = _OUTPUT_DNSSIM_CONN_CLOSING;

    if (conn->handshake_timer != NULL) {
        uv_timer_stop(conn->handshake_timer);
        uv_close((uv_handle_t*)conn->handshake_timer, _on_handshake_timer_closed);
    }
    if (conn->idle_timer != NULL) {
        conn->is_idle = false;
        uv_timer_stop(conn->idle_timer);
        uv_close((uv_handle_t*)conn->idle_timer, _on_idle_timer_closed);
    }

    switch (_self->transport) {
    case OUTPUT_DNSSIM_TRANSPORT_TCP:
        _output_dnssim_tcp_close(conn);
        break;
    case OUTPUT_DNSSIM_TRANSPORT_TLS:
#if GNUTLS_VERSION_NUMBER >= DNSSIM_MIN_GNUTLS_VERSION
        _output_dnssim_tls_close(conn);
#else
        lfatal(DNSSIM_MIN_GNUTLS_ERRORMSG);
#endif
        break;
    case OUTPUT_DNSSIM_TRANSPORT_HTTPS2:
#if GNUTLS_VERSION_NUMBER >= DNSSIM_MIN_GNUTLS_VERSION
        _output_dnssim_https2_close(conn);
#else
        lfatal(DNSSIM_MIN_GNUTLS_ERRORMSG);
#endif
        break;
    default:
        lfatal("unsupported transport");
        break;
    }
}

/* Close connection or run idle timer when there are no more outstanding queries. */
void _output_dnssim_conn_idle(_output_dnssim_connection_t* conn)
{
    mlassert(conn, "conn can't be nil");

    if (conn->queued == NULL && conn->sent == NULL) {
        if (conn->idle_timer == NULL)
            _output_dnssim_conn_close(conn);
        else if (!conn->is_idle) {
            conn->is_idle = true;
            uv_timer_again(conn->idle_timer);
        }
    }
}

static void _send_pending_queries(_output_dnssim_connection_t* conn)
{
    _output_dnssim_query_tcp_t* qry;
    mlassert(conn, "conn is nil");
    mlassert(conn->client, "conn->client is nil");
    qry = (_output_dnssim_query_tcp_t*)conn->client->pending;

    while (qry != NULL && conn->state == _OUTPUT_DNSSIM_CONN_ACTIVE) {
        _output_dnssim_query_tcp_t* next = (_output_dnssim_query_tcp_t*)qry->qry.next;
        if (qry->qry.state == _OUTPUT_DNSSIM_QUERY_PENDING_WRITE) {
            switch (qry->qry.transport) {
            case OUTPUT_DNSSIM_TRANSPORT_TCP:
                _output_dnssim_tcp_write_query(conn, qry);
                break;
            case OUTPUT_DNSSIM_TRANSPORT_TLS:
#if GNUTLS_VERSION_NUMBER >= DNSSIM_MIN_GNUTLS_VERSION
                _output_dnssim_tls_write_query(conn, qry);
#else
                mlfatal(DNSSIM_MIN_GNUTLS_ERRORMSG);
#endif
                break;
            case OUTPUT_DNSSIM_TRANSPORT_HTTPS2:
#if GNUTLS_VERSION_NUMBER >= DNSSIM_MIN_GNUTLS_VERSION
                _output_dnssim_https2_write_query(conn, qry);
#else
                mlfatal(DNSSIM_MIN_GNUTLS_ERRORMSG);
#endif
                break;
            default:
                mlfatal("unsupported protocol");
                break;
            }
        }
        qry = next;
    }
}

int _output_dnssim_handle_pending_queries(_output_dnssim_client_t* client)
{
    int ret = 0;
    mlassert(client, "client is nil");

    if (client->pending == NULL)
        return ret;

    output_dnssim_t* self = client->dnssim;
    mlassert(self, "client must belong to dnssim");

    /* Get active connection or find out whether new connection has to be opened. */
    bool                         is_connecting = false;
    _output_dnssim_connection_t* conn          = client->conn;
    while (conn != NULL) {
        if (conn->state == _OUTPUT_DNSSIM_CONN_ACTIVE)
            break;
        else if (_conn_is_connecting(conn))
            is_connecting = true;
        conn = conn->next;
    }

    if (conn != NULL) { /* Send data right away over active connection. */
        _send_pending_queries(conn);
    } else if (!is_connecting) { /* No active or connecting connection -> open a new one. */
        lfatal_oom(conn = calloc(1, sizeof(_output_dnssim_connection_t)));
        conn->state  = _OUTPUT_DNSSIM_CONN_INITIALIZED;
        conn->client = client;
        conn->stats  = self->stats_current;
        if (_self->transport == OUTPUT_DNSSIM_TRANSPORT_TLS) {
#if GNUTLS_VERSION_NUMBER >= DNSSIM_MIN_GNUTLS_VERSION
            ret = _output_dnssim_tls_init(conn);
            if (ret < 0) {
                free(conn);
                return ret;
            }
#else
            lfatal(DNSSIM_MIN_GNUTLS_ERRORMSG);
#endif
        } else if (_self->transport == OUTPUT_DNSSIM_TRANSPORT_HTTPS2) {
#if GNUTLS_VERSION_NUMBER >= DNSSIM_MIN_GNUTLS_VERSION
            ret = _output_dnssim_https2_init(conn);
            if (ret < 0) {
                free(conn);
                return ret;
            }
#else
            lfatal(DNSSIM_MIN_GNUTLS_ERRORMSG);
#endif
        }
        ret = _output_dnssim_tcp_connect(self, conn);
        if (ret < 0)
            return ret;
        _ll_append(client->conn, conn);
    } /* Otherwise, pending queries wil be sent after connected callback. */

    return ret;
}

void _output_dnssim_conn_activate(_output_dnssim_connection_t* conn)
{
    mlassert(conn, "conn is nil");
    mlassert(conn->client, "conn must be associated with a client");
    mlassert(conn->client->dnssim, "client must be associated with dnssim");

    uv_timer_stop(conn->handshake_timer);

    conn->state = _OUTPUT_DNSSIM_CONN_ACTIVE;
    conn->client->dnssim->stats_current->conn_active++;
    conn->read_state            = _OUTPUT_DNSSIM_READ_STATE_DNSLEN;
    conn->dnsbuf_len            = 2;
    conn->dnsbuf_pos            = 0;
    conn->dnsbuf_free_after_use = false;

    _send_pending_queries(conn);
    _output_dnssim_conn_idle(conn);
}

int _process_dnsmsg(_output_dnssim_connection_t* conn)
{
    mlassert(conn, "conn can't be nil");
    mlassert(conn->client, "conn must have client");
    mlassert(conn->client->dnssim, "client must have dnssim");

    output_dnssim_t* self = conn->client->dnssim;

    core_object_payload_t payload = CORE_OBJECT_PAYLOAD_INIT(NULL);
    core_object_dns_t     dns_a   = CORE_OBJECT_DNS_INIT(&payload);

    payload.payload = (uint8_t*)conn->dnsbuf_data;
    payload.len     = conn->dnsbuf_len;

    dns_a.obj_prev = (core_object_t*)&payload;
    int ret        = core_object_dns_parse_header(&dns_a);
    if (ret != 0) {
        lwarning("tcp response malformed");
        return _ERR_MALFORMED;
    }
    ldebug("tcp recv dnsmsg id: %04x", dns_a.id);

    _output_dnssim_query_t* qry;

    if (_self->transport == OUTPUT_DNSSIM_TRANSPORT_HTTPS2) {
        lassert(conn->http2, "conn must have http2 ctx");
        lassert(conn->http2->current_qry, "http2 has no current_qry");
        lassert(conn->http2->current_qry->qry.req, "current_qry has no req");
        lassert(conn->http2->current_qry->qry.req->dns_q, "req has no dns_q");

        ret = _output_dnssim_answers_request(conn->http2->current_qry->qry.req, &dns_a);
        switch (ret) {
        case 0:
            _output_dnssim_request_answered(conn->http2->current_qry->qry.req, &dns_a);
            break;
        case _ERR_MSGID:
            lwarning("https2 QID mismatch: request=0x%04x, response=0x%04x",
                conn->http2->current_qry->qry.req->dns_q->id, dns_a.id);
            break;
        case _ERR_QUESTION:
        default:
            lwarning("https2 response question mismatch");
            break;
        }
    } else {
        qry = conn->sent;
        while (qry != NULL) {
            if (qry->req->dns_q->id == dns_a.id) {
                ret = _output_dnssim_answers_request(qry->req, &dns_a);
                if (ret != 0) {
                    lwarning("response question mismatch");
                } else {
                    _output_dnssim_request_answered(qry->req, &dns_a);
                }
                break;
            }
            qry = qry->next;
        }
    }

    return 0;
}

static int _parse_dnsbuf_data(_output_dnssim_connection_t* conn)
{
    mlassert(conn, "conn can't be nil");
    mlassert(conn->dnsbuf_pos == conn->dnsbuf_len, "attempt to parse incomplete dnsbuf_data");
    int ret = 0;

    switch (conn->read_state) {
    case _OUTPUT_DNSSIM_READ_STATE_DNSLEN: {
        uint16_t* p_dnslen = (uint16_t*)conn->dnsbuf_data;
        conn->dnsbuf_len   = ntohs(*p_dnslen);
        if (conn->dnsbuf_len == 0) {
            mlwarning("invalid dnslen received: 0");
            conn->dnsbuf_len = 2;
            conn->read_state = _OUTPUT_DNSSIM_READ_STATE_DNSLEN;
        } else if (conn->dnsbuf_len < 12) {
            mldebug("invalid dnslen received: %d", conn->dnsbuf_len);
            ret = -1;
        } else {
            mldebug("dnslen: %d", conn->dnsbuf_len);
            conn->read_state = _OUTPUT_DNSSIM_READ_STATE_DNSMSG;
        }
        break;
    }
    case _OUTPUT_DNSSIM_READ_STATE_DNSMSG:
        ret = _process_dnsmsg(conn);
        if (ret) {
            conn->read_state = _OUTPUT_DNSSIM_READ_STATE_INVALID;
        } else {
            conn->dnsbuf_len = 2;
            conn->read_state = _OUTPUT_DNSSIM_READ_STATE_DNSLEN;
        }
        break;
    default:
        mlfatal("tcp invalid connection read_state");
        break;
    }

    conn->dnsbuf_pos = 0;
    if (conn->dnsbuf_free_after_use) {
        conn->dnsbuf_free_after_use = false;
        free(conn->dnsbuf_data);
    }
    conn->dnsbuf_data = NULL;

    return ret;
}

static unsigned int _read_dns_stream_chunk(_output_dnssim_connection_t* conn, size_t len, const char* data)
{
    mlassert(conn, "conn can't be nil");
    mlassert(data, "data can't be nil");
    mlassert(len > 0, "no data to read");
    mlassert((conn->read_state == _OUTPUT_DNSSIM_READ_STATE_DNSLEN || conn->read_state == _OUTPUT_DNSSIM_READ_STATE_DNSMSG),
        "connection has invalid read_state");

    int          ret = 0;
    unsigned int nread;
    size_t       expected = conn->dnsbuf_len - conn->dnsbuf_pos;
    mlassert(expected > 0, "no data expected");

    if (conn->dnsbuf_free_after_use == false && expected > len) {
        /* Start of partial read. */
        mlassert(conn->dnsbuf_pos == 0, "conn->dnsbuf_pos must be 0 at start of partial read");
        mlassert(conn->dnsbuf_len > 0, "conn->dnsbuf_len must be set at start of partial read");
        mlfatal_oom(conn->dnsbuf_data = malloc(conn->dnsbuf_len * sizeof(char)));
        conn->dnsbuf_free_after_use = true;
    }

    if (conn->dnsbuf_free_after_use) { /* Partial read is in progress. */
        char* dest = conn->dnsbuf_data + conn->dnsbuf_pos;
        if (expected < len)
            len = expected;
        memcpy(dest, data, len);
        conn->dnsbuf_pos += len;
        nread = len;
    } else { /* Complete and clean read. */
        mlassert(expected <= len, "not enough data to perform complete read");
        conn->dnsbuf_data = (char*)data;
        conn->dnsbuf_pos  = conn->dnsbuf_len;
        nread             = expected;
    }

    /* If entire dnslen/dnsmsg was read, attempt to parse it. */
    if (conn->dnsbuf_len == conn->dnsbuf_pos) {
        ret = _parse_dnsbuf_data(conn);
        if (ret < 0)
            return ret;
    }

    return nread;
}

void _output_dnssim_read_dns_stream(_output_dnssim_connection_t* conn, size_t len, const char* data)
{
    int pos   = 0;
    int chunk = 0;
    while (pos < len) {
        chunk = _read_dns_stream_chunk(conn, len - pos, data + pos);
        if (chunk < 0) {
            mlwarning("lost orientation in DNS stream, closing");
            _output_dnssim_conn_close(conn);
            break;
        } else {
            pos += chunk;
        }
    }
    mlassert((pos == len) || (chunk < 0), "dns stream read invalid, pos != len");
}

void _output_dnssim_read_dnsmsg(_output_dnssim_connection_t* conn, size_t len, const char* data)
{
    mlassert(conn, "conn is nil");
    mlassert(len > 0, "len is zero");
    mlassert(data, "no data");
    mlassert(conn->dnsbuf_pos == 0, "dnsbuf not empty");
    mlassert(conn->dnsbuf_free_after_use == false, "dnsbuf read in progress");

    /* Read dnsmsg of given length from input data. */
    conn->dnsbuf_len = len;
    conn->read_state = _OUTPUT_DNSSIM_READ_STATE_DNSMSG;
    int nread        = _read_dns_stream_chunk(conn, len, data);

    if (nread != len) {
        mlwarning("failed to read received dnsmsg");
        if (conn->dnsbuf_free_after_use)
            free(conn->dnsbuf_data);
    }

    /* Clean state afterwards. */
    conn->read_state            = _OUTPUT_DNSSIM_READ_STATE_DNSLEN;
    conn->dnsbuf_len            = 2;
    conn->dnsbuf_pos            = 0;
    conn->dnsbuf_free_after_use = false;
}