Coverage Report

Created: 2026-04-15 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/boringssl/ssl/d1_both.cc
Line
Count
Source
1
// Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#include <openssl/ssl.h>
16
17
#include <assert.h>
18
#include <limits.h>
19
#include <string.h>
20
21
#include <algorithm>
22
23
#include <openssl/err.h>
24
#include <openssl/evp.h>
25
#include <openssl/mem.h>
26
#include <openssl/rand.h>
27
28
#include "../crypto/bytestring/internal.h"
29
#include "../crypto/internal.h"
30
#include "../crypto/bytestring/internal.h"
31
#include "internal.h"
32
33
34
BSSL_NAMESPACE_BEGIN
35
36
// TODO(davidben): 28 comes from the size of IP + UDP header. Is this reasonable
37
// for these values? Notably, why is kMinMTU a function of the transport
38
// protocol's overhead rather than, say, what's needed to hold a minimally-sized
39
// handshake fragment plus protocol overhead.
40
41
// kMinMTU is the minimum acceptable MTU value.
42
static const unsigned int kMinMTU = 256 - 28;
43
44
// kDefaultMTU is the default MTU value to use if neither the user nor
45
// the underlying BIO supplies one.
46
static const unsigned int kDefaultMTU = 1500 - 28;
47
48
// BitRange returns a |uint8_t| with bits |start|, inclusive, to |end|,
49
// exclusive, set.
50
232k
static uint8_t BitRange(size_t start, size_t end) {
51
232k
  assert(start <= end && end <= 8);
52
232k
  return static_cast<uint8_t>(~((1u << start) - 1) & ((1u << end) - 1));
53
232k
}
54
55
// FirstUnmarkedRangeInByte returns the first unmarked range in bits |b|.
56
66.3k
static DTLSMessageBitmap::Range FirstUnmarkedRangeInByte(uint8_t b) {
57
66.3k
  size_t start, end;
58
111k
  for (start = 0; start < 8; start++) {
59
111k
    if ((b & (1u << start)) == 0) {
60
66.3k
      break;
61
66.3k
    }
62
111k
  }
63
375k
  for (end = start; end < 8; end++) {
64
341k
    if ((b & (1u << end)) != 0) {
65
33.0k
      break;
66
33.0k
    }
67
341k
  }
68
66.3k
  return DTLSMessageBitmap::Range{start, end};
69
66.3k
}
70
71
82.3k
bool DTLSMessageBitmap::Init(size_t num_bits) {
72
82.3k
  if (num_bits + 7 < num_bits) {
73
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
74
0
    return false;
75
0
  }
76
82.3k
  size_t num_bytes = (num_bits + 7) / 8;
77
82.3k
  size_t bits_rounded = num_bytes * 8;
78
82.3k
  if (!bytes_.Init(num_bytes)) {
79
0
    return false;
80
0
  }
81
82.3k
  MarkRange(num_bits, bits_rounded);
82
82.3k
  first_unmarked_byte_ = 0;
83
82.3k
  return true;
84
82.3k
}
85
86
159k
void DTLSMessageBitmap::MarkRange(size_t start, size_t end) {
87
159k
  assert(start <= end);
88
  // Don't bother touching bytes that have already been marked.
89
159k
  start = std::max(start, first_unmarked_byte_ << 3);
90
  // Clamp everything within range.
91
159k
  start = std::min(start, bytes_.size() << 3);
92
159k
  end = std::min(end, bytes_.size() << 3);
93
159k
  if (start >= end) {
94
9.61k
    return;
95
9.61k
  }
96
97
149k
  if ((start >> 3) == (end >> 3)) {
98
49.2k
    bytes_[start >> 3] |= BitRange(start & 7, end & 7);
99
100k
  } else {
100
100k
    bytes_[start >> 3] |= BitRange(start & 7, 8);
101
817k
    for (size_t i = (start >> 3) + 1; i < (end >> 3); i++) {
102
717k
      bytes_[i] = 0xff;
103
717k
    }
104
100k
    if ((end & 7) != 0) {
105
18.5k
      bytes_[end >> 3] |= BitRange(0, end & 7);
106
18.5k
    }
107
100k
  }
108
109
  // Maintain the |first_unmarked_byte_| invariant. This work is amortized
110
  // across all |MarkRange| calls.
111
936k
  while (first_unmarked_byte_ < bytes_.size() &&
112
886k
         bytes_[first_unmarked_byte_] == 0xff) {
113
787k
    first_unmarked_byte_++;
114
787k
  }
115
  // If the whole message is marked, we no longer need to spend memory on the
116
  // bitmap.
117
149k
  if (first_unmarked_byte_ >= bytes_.size()) {
118
50.6k
    bytes_.Reset();
119
50.6k
    first_unmarked_byte_ = 0;
120
50.6k
  }
121
149k
}
122
123
DTLSMessageBitmap::Range DTLSMessageBitmap::NextUnmarkedRange(
124
69.2k
    size_t start) const {
125
  // Don't bother looking at bytes that are known to be fully marked.
126
69.2k
  start = std::max(start, first_unmarked_byte_ << 3);
127
128
69.2k
  size_t idx = start >> 3;
129
69.2k
  if (idx >= bytes_.size()) {
130
4.84k
    return Range{0, 0};
131
4.84k
  }
132
133
  // Look at the bits from |start| up to a byte boundary.
134
64.4k
  uint8_t byte = bytes_[idx] | BitRange(0, start & 7);
135
64.4k
  if (byte == 0xff) {
136
    // Nothing unmarked at this byte. Keep searching for an unmarked bit.
137
26.4k
    for (idx = idx + 1; idx < bytes_.size(); idx++) {
138
0
      if (bytes_[idx] != 0xff) {
139
0
        byte = bytes_[idx];
140
0
        break;
141
0
      }
142
0
    }
143
26.4k
    if (idx >= bytes_.size()) {
144
26.4k
      return Range{0, 0};
145
26.4k
    }
146
26.4k
  }
147
148
37.9k
  Range range = FirstUnmarkedRangeInByte(byte);
149
37.9k
  assert(!range.empty());
150
37.9k
  bool should_extend = range.end == 8;
151
37.9k
  range.start += idx << 3;
152
37.9k
  range.end += idx << 3;
153
37.9k
  if (!should_extend) {
154
    // The range did not end at a byte boundary. We're done.
155
4.67k
    return range;
156
4.67k
  }
157
158
  // Collect all fully unmarked bytes.
159
1.96M
  for (idx = idx + 1; idx < bytes_.size(); idx++) {
160
1.95M
    if (bytes_[idx] != 0) {
161
28.4k
      break;
162
28.4k
    }
163
1.95M
  }
164
33.2k
  range.end = idx << 3;
165
166
  // Add any bits from the remaining byte, if any.
167
33.2k
  if (idx < bytes_.size()) {
168
28.4k
    Range extra = FirstUnmarkedRangeInByte(bytes_[idx]);
169
28.4k
    if (extra.start == 0) {
170
28.4k
      range.end += extra.end;
171
28.4k
    }
172
28.4k
  }
173
174
33.2k
  return range;
175
37.9k
}
176
177
// Receiving handshake messages.
178
179
static UniquePtr<DTLSIncomingMessage> dtls_new_incoming_message(
180
51.5k
    const struct hm_header_st *msg_hdr) {
181
51.5k
  ScopedCBB cbb;
182
51.5k
  UniquePtr<DTLSIncomingMessage> frag = MakeUnique<DTLSIncomingMessage>();
183
51.5k
  if (!frag) {
184
0
    return nullptr;
185
0
  }
186
51.5k
  frag->type = msg_hdr->type;
187
51.5k
  frag->seq = msg_hdr->seq;
188
189
  // Allocate space for the reassembled message and fill in the header.
190
51.5k
  if (!frag->data.InitForOverwrite(DTLS1_HM_HEADER_LENGTH + msg_hdr->msg_len)) {
191
0
    return nullptr;
192
0
  }
193
194
51.5k
  if (!CBB_init_fixed(cbb.get(), frag->data.data(), DTLS1_HM_HEADER_LENGTH) ||
195
51.5k
      !CBB_add_u8(cbb.get(), msg_hdr->type) ||
196
51.5k
      !CBB_add_u24(cbb.get(), msg_hdr->msg_len) ||
197
51.5k
      !CBB_add_u16(cbb.get(), msg_hdr->seq) ||
198
51.5k
      !CBB_add_u24(cbb.get(), 0 /* frag_off */) ||
199
51.5k
      !CBB_add_u24(cbb.get(), msg_hdr->msg_len) ||
200
51.5k
      !CBB_finish(cbb.get(), nullptr, nullptr)) {
201
0
    return nullptr;
202
0
  }
203
204
51.5k
  if (!frag->reassembly.Init(msg_hdr->msg_len)) {
205
0
    return nullptr;
206
0
  }
207
208
51.5k
  return frag;
209
51.5k
}
210
211
// dtls1_is_current_message_complete returns whether the current handshake
212
// message is complete.
213
395k
static bool dtls1_is_current_message_complete(const SSL *ssl) {
214
395k
  size_t idx = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
215
395k
  DTLSIncomingMessage *frag = ssl->d1->incoming_messages[idx].get();
216
395k
  return frag != nullptr && frag->reassembly.IsComplete();
217
395k
}
218
219
// dtls1_get_incoming_message returns the incoming message corresponding to
220
// |msg_hdr|. If none exists, it creates a new one and inserts it in the
221
// queue. Otherwise, it checks |msg_hdr| is consistent with the existing one. It
222
// returns NULL on failure. The caller does not take ownership of the result.
223
static DTLSIncomingMessage *dtls1_get_incoming_message(
224
78.0k
    SSL *ssl, uint8_t *out_alert, const struct hm_header_st *msg_hdr) {
225
78.0k
  if (msg_hdr->seq < ssl->d1->handshake_read_seq ||
226
78.0k
      msg_hdr->seq - ssl->d1->handshake_read_seq >= SSL_MAX_HANDSHAKE_FLIGHT) {
227
4
    *out_alert = SSL_AD_INTERNAL_ERROR;
228
4
    return nullptr;
229
4
  }
230
231
78.0k
  size_t idx = msg_hdr->seq % SSL_MAX_HANDSHAKE_FLIGHT;
232
78.0k
  DTLSIncomingMessage *frag = ssl->d1->incoming_messages[idx].get();
233
78.0k
  if (frag != nullptr) {
234
26.4k
    assert(frag->seq == msg_hdr->seq);
235
    // The new fragment must be compatible with the previous fragments from this
236
    // message.
237
26.4k
    if (frag->type != msg_hdr->type ||  //
238
26.4k
        frag->msg_len() != msg_hdr->msg_len) {
239
78
      OPENSSL_PUT_ERROR(SSL, SSL_R_FRAGMENT_MISMATCH);
240
78
      *out_alert = SSL_AD_ILLEGAL_PARAMETER;
241
78
      return nullptr;
242
78
    }
243
26.3k
    return frag;
244
26.4k
  }
245
246
  // This is the first fragment from this message.
247
51.5k
  ssl->d1->incoming_messages[idx] = dtls_new_incoming_message(msg_hdr);
248
51.5k
  if (!ssl->d1->incoming_messages[idx]) {
249
0
    *out_alert = SSL_AD_INTERNAL_ERROR;
250
0
    return nullptr;
251
0
  }
252
51.5k
  return ssl->d1->incoming_messages[idx].get();
253
51.5k
}
254
255
bool dtls1_process_handshake_fragments(SSL *ssl, uint8_t *out_alert,
256
                                       DTLSRecordNumber record_number,
257
107k
                                       Span<const uint8_t> record) {
258
107k
  bool implicit_ack = false;
259
107k
  bool skipped_fragments = false;
260
107k
  CBS cbs = record;
261
211k
  while (CBS_len(&cbs) > 0) {
262
    // Read a handshake fragment.
263
104k
    struct hm_header_st msg_hdr;
264
104k
    CBS body;
265
104k
    if (!dtls1_parse_fragment(&cbs, &msg_hdr, &body)) {
266
198
      OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HANDSHAKE_RECORD);
267
198
      *out_alert = SSL_AD_DECODE_ERROR;
268
198
      return false;
269
198
    }
270
271
104k
    const size_t frag_off = msg_hdr.frag_off;
272
104k
    const size_t frag_len = msg_hdr.frag_len;
273
104k
    const size_t msg_len = msg_hdr.msg_len;
274
104k
    if (frag_off > msg_len || frag_len > msg_len - frag_off) {
275
63
      OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HANDSHAKE_RECORD);
276
63
      *out_alert = SSL_AD_ILLEGAL_PARAMETER;
277
63
      return false;
278
63
    }
279
280
104k
    if (msg_hdr.seq < ssl->d1->handshake_read_seq ||
281
79.0k
        ssl->d1->handshake_read_overflow) {
282
      // Ignore fragments from the past. This is a retransmit of data we already
283
      // received.
284
      //
285
      // TODO(crbug.com/383016430): Use this to drive retransmits.
286
25.1k
      continue;
287
25.1k
    }
288
289
79.0k
    if (record_number.epoch() != ssl->d1->read_epoch.epoch ||
290
79.0k
        ssl->d1->next_read_epoch != nullptr) {
291
      // New messages can only arrive in the latest epoch. This can fail if the
292
      // record came from |prev_read_epoch|, or if it came from |read_epoch| but
293
      // |next_read_epoch| exists. (It cannot come from |next_read_epoch|
294
      // because |next_read_epoch| becomes |read_epoch| once it receives a
295
      // record.)
296
10
      OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
297
10
      *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
298
10
      return false;
299
10
    }
300
301
79.0k
    if (msg_len > ssl_max_handshake_message_len(ssl)) {
302
47
      OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESSIVE_MESSAGE_SIZE);
303
47
      *out_alert = SSL_AD_ILLEGAL_PARAMETER;
304
47
      return false;
305
47
    }
306
307
78.9k
    if (SSL_in_init(ssl) && ssl_has_final_version(ssl) &&
308
30.2k
        ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
309
      // During the handshake, if we receive any portion of the next flight, the
310
      // peer must have received our most recent flight. In DTLS 1.3, this is an
311
      // implicit ACK. See RFC 9147, Section 7.1.
312
      //
313
      // This only applies during the handshake. After the handshake, the next
314
      // message may be part of a post-handshake transaction. It also does not
315
      // apply immediately after the handshake. As a client, receiving a
316
      // KeyUpdate or NewSessionTicket does not imply the server has received
317
      // our Finished. The server may have sent those messages in half-RTT.
318
20.4k
      implicit_ack = true;
319
20.4k
    }
320
321
78.9k
    if (msg_hdr.seq - ssl->d1->handshake_read_seq > SSL_MAX_HANDSHAKE_FLIGHT) {
322
      // Ignore fragments too far in the future.
323
935
      skipped_fragments = true;
324
935
      continue;
325
935
    }
326
327
78.0k
    DTLSIncomingMessage *frag =
328
78.0k
        dtls1_get_incoming_message(ssl, out_alert, &msg_hdr);
329
78.0k
    if (frag == nullptr) {
330
82
      return false;
331
82
    }
332
78.0k
    assert(frag->msg_len() == msg_len);
333
334
77.9k
    if (frag->reassembly.IsComplete()) {
335
      // The message is already assembled.
336
1.28k
      continue;
337
1.28k
    }
338
77.9k
    assert(msg_len > 0);
339
340
    // Copy the body into the fragment.
341
76.6k
    Span<uint8_t> dest = frag->msg().subspan(frag_off, CBS_len(&body));
342
76.6k
    assert(dest.size() == CBS_len(&body));
343
76.6k
    OPENSSL_memcpy(dest.data(), CBS_data(&body), CBS_len(&body));
344
76.6k
    frag->reassembly.MarkRange(frag_off, frag_off + frag_len);
345
76.6k
  }
346
347
106k
  if (implicit_ack) {
348
20.4k
    dtls1_stop_timer(ssl);
349
20.4k
    dtls_clear_outgoing_messages(ssl);
350
20.4k
  }
351
352
106k
  if (!skipped_fragments) {
353
106k
    ssl->d1->records_to_ack.PushBack(record_number);
354
355
106k
    if (ssl_has_final_version(ssl) &&
356
88.3k
        ssl_protocol_version(ssl) >= TLS1_3_VERSION &&
357
76.6k
        !ssl->d1->ack_timer.IsSet() && !ssl->d1->sending_ack) {
358
      // Schedule sending an ACK. The delay serves several purposes:
359
      // - If there are more records to come, we send only one ACK.
360
      // - If there are more records to come and the flight is now complete, we
361
      //   will send the reply (which implicitly ACKs the previous flight) and
362
      //   cancel the timer.
363
      // - If there are more records to come, the flight is now complete, but
364
      //   generating the response is delayed (e.g. a slow, async private key),
365
      //   the timer will fire and we send an ACK anyway.
366
4.95k
      OPENSSL_timeval now = ssl_ctx_get_current_time(ssl->ctx.get());
367
4.95k
      ssl->d1->ack_timer.StartMicroseconds(
368
4.95k
          now, uint64_t{ssl->d1->timeout_duration_ms} * 1000 / 4);
369
4.95k
    }
370
106k
  }
371
372
106k
  return true;
373
107k
}
374
375
ssl_open_record_t dtls1_open_handshake(SSL *ssl, size_t *out_consumed,
376
199k
                                       uint8_t *out_alert, Span<uint8_t> in) {
377
199k
  uint8_t type;
378
199k
  DTLSRecordNumber record_number;
379
199k
  Span<uint8_t> record;
380
199k
  auto ret = dtls_open_record(ssl, &type, &record_number, &record, out_consumed,
381
199k
                              out_alert, in);
382
199k
  if (ret != ssl_open_record_success) {
383
122k
    return ret;
384
122k
  }
385
386
77.2k
  switch (type) {
387
265
    case SSL3_RT_APPLICATION_DATA:
388
      // In DTLS 1.2, out-of-order application data may be received between
389
      // ChangeCipherSpec and Finished. Discard it.
390
265
      return ssl_open_record_discard;
391
392
564
    case SSL3_RT_CHANGE_CIPHER_SPEC:
393
564
      if (record.size() != 1u || record[0] != SSL3_MT_CCS) {
394
57
        OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_CHANGE_CIPHER_SPEC);
395
57
        *out_alert = SSL_AD_ILLEGAL_PARAMETER;
396
57
        return ssl_open_record_error;
397
57
      }
398
399
      // We do not support renegotiation, so encrypted ChangeCipherSpec records
400
      // are illegal.
401
507
      if (record_number.epoch() != 0) {
402
2
        OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
403
2
        *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
404
2
        return ssl_open_record_error;
405
2
      }
406
407
      // Ignore ChangeCipherSpec from a previous epoch.
408
505
      if (record_number.epoch() != ssl->d1->read_epoch.epoch) {
409
0
        return ssl_open_record_discard;
410
0
      }
411
412
      // Flag the ChangeCipherSpec for later.
413
      // TODO(crbug.com/383078468): Should we reject this in DTLS 1.3?
414
505
      ssl->d1->has_change_cipher_spec = true;
415
505
      ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_CHANGE_CIPHER_SPEC,
416
505
                          record);
417
505
      return ssl_open_record_success;
418
419
743
    case SSL3_RT_ACK:
420
743
      return dtls1_process_ack(ssl, out_alert, record_number, record);
421
422
75.6k
    case SSL3_RT_HANDSHAKE:
423
75.6k
      if (!dtls1_process_handshake_fragments(ssl, out_alert, record_number,
424
75.6k
                                             record)) {
425
371
        return ssl_open_record_error;
426
371
      }
427
75.2k
      return ssl_open_record_success;
428
429
103
    default:
430
103
      OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
431
103
      *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
432
103
      return ssl_open_record_error;
433
77.2k
  }
434
77.2k
}
435
436
308k
bool dtls1_get_message(const SSL *ssl, SSLMessage *out) {
437
308k
  if (!dtls1_is_current_message_complete(ssl)) {
438
233k
    return false;
439
233k
  }
440
441
74.7k
  size_t idx = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
442
74.7k
  const DTLSIncomingMessage *frag = ssl->d1->incoming_messages[idx].get();
443
74.7k
  out->type = frag->type;
444
74.7k
  out->raw = CBS(frag->data);
445
74.7k
  out->body = CBS(frag->msg());
446
74.7k
  out->is_v2_hello = false;
447
74.7k
  if (!ssl->s3->has_message) {
448
50.6k
    ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_HANDSHAKE, out->raw);
449
50.6k
    ssl->s3->has_message = true;
450
50.6k
  }
451
74.7k
  return true;
452
308k
}
453
454
47.6k
void dtls1_next_message(SSL *ssl) {
455
47.6k
  assert(ssl->s3->has_message);
456
47.6k
  assert(dtls1_is_current_message_complete(ssl));
457
47.6k
  size_t index = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
458
47.6k
  ssl->d1->incoming_messages[index].reset();
459
47.6k
  ssl->d1->handshake_read_seq++;
460
47.6k
  if (ssl->d1->handshake_read_seq == 0) {
461
0
    ssl->d1->handshake_read_overflow = true;
462
0
  }
463
47.6k
  ssl->s3->has_message = false;
464
  // If we previously sent a flight, mark it as having a reply, so
465
  // |on_handshake_complete| can manage post-handshake retransmission.
466
47.6k
  if (ssl->d1->outgoing_messages_complete) {
467
31.5k
    ssl->d1->flight_has_reply = true;
468
31.5k
  }
469
47.6k
}
470
471
42.9k
bool dtls_has_unprocessed_handshake_data(const SSL *ssl) {
472
42.9k
  size_t current = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
473
343k
  for (size_t i = 0; i < SSL_MAX_HANDSHAKE_FLIGHT; i++) {
474
    // Skip the current message.
475
300k
    if (ssl->s3->has_message && i == current) {
476
39.4k
      assert(dtls1_is_current_message_complete(ssl));
477
39.4k
      continue;
478
39.4k
    }
479
261k
    if (ssl->d1->incoming_messages[i] != nullptr) {
480
26
      return true;
481
26
    }
482
261k
  }
483
42.9k
  return false;
484
42.9k
}
485
486
bool dtls1_parse_fragment(CBS *cbs, struct hm_header_st *out_hdr,
487
142k
                          CBS *out_body) {
488
142k
  OPENSSL_memset(out_hdr, 0x00, sizeof(struct hm_header_st));
489
490
142k
  if (!CBS_get_u8(cbs, &out_hdr->type) ||
491
142k
      !CBS_get_u24(cbs, &out_hdr->msg_len) ||
492
142k
      !CBS_get_u16(cbs, &out_hdr->seq) ||
493
142k
      !CBS_get_u24(cbs, &out_hdr->frag_off) ||
494
142k
      !CBS_get_u24(cbs, &out_hdr->frag_len) ||
495
142k
      !CBS_get_bytes(cbs, out_body, out_hdr->frag_len)) {
496
208
    return false;
497
208
  }
498
499
142k
  return true;
500
142k
}
501
502
ssl_open_record_t dtls1_open_change_cipher_spec(SSL *ssl, size_t *out_consumed,
503
                                                uint8_t *out_alert,
504
2.79k
                                                Span<uint8_t> in) {
505
2.79k
  if (!ssl->d1->has_change_cipher_spec) {
506
    // dtls1_open_handshake processes both handshake and ChangeCipherSpec.
507
2.78k
    auto ret = dtls1_open_handshake(ssl, out_consumed, out_alert, in);
508
2.78k
    if (ret != ssl_open_record_success) {
509
2.08k
      return ret;
510
2.08k
    }
511
2.78k
  }
512
711
  if (ssl->d1->has_change_cipher_spec) {
513
316
    ssl->d1->has_change_cipher_spec = false;
514
316
    return ssl_open_record_success;
515
316
  }
516
395
  return ssl_open_record_discard;
517
711
}
518
519
520
// Sending handshake messages.
521
522
23.5k
void dtls_clear_outgoing_messages(SSL *ssl) {
523
23.5k
  ssl->d1->outgoing_messages.clear();
524
23.5k
  ssl->d1->sent_records = nullptr;
525
23.5k
  ssl->d1->outgoing_written = 0;
526
23.5k
  ssl->d1->outgoing_offset = 0;
527
23.5k
  ssl->d1->outgoing_messages_complete = false;
528
23.5k
  ssl->d1->flight_has_reply = false;
529
23.5k
  ssl->d1->sending_flight = false;
530
23.5k
  dtls_clear_unused_write_epochs(ssl);
531
23.5k
}
532
533
32.6k
void dtls_clear_unused_write_epochs(SSL *ssl) {
534
32.6k
  ssl->d1->extra_write_epochs.EraseIf(
535
32.6k
      [ssl](const UniquePtr<DTLSWriteEpoch> &write_epoch) -> bool {
536
        // Non-current epochs may be discarded once there are no incomplete
537
        // outgoing messages that reference them.
538
        //
539
        // TODO(crbug.com/381113363): Epoch 1 (0-RTT) should be retained until
540
        // epoch 3 (app data) is available.
541
18.0k
        for (const auto &msg : ssl->d1->outgoing_messages) {
542
14.3k
          if (msg.epoch == write_epoch->epoch() && !msg.IsFullyAcked()) {
543
11.3k
            return false;
544
11.3k
          }
545
14.3k
        }
546
6.65k
        return true;
547
18.0k
      });
548
32.6k
}
549
550
30.9k
bool dtls1_init_message(const SSL *ssl, CBB *cbb, CBB *body, uint8_t type) {
551
  // Pick a modest size hint to save most of the |realloc| calls.
552
30.9k
  if (!CBB_init(cbb, 64) ||                                   //
553
30.9k
      !CBB_add_u8(cbb, type) ||                               //
554
30.9k
      !CBB_add_u24(cbb, 0 /* length (filled in later) */) ||  //
555
30.9k
      !CBB_add_u16(cbb, ssl->d1->handshake_write_seq) ||      //
556
30.9k
      !CBB_add_u24(cbb, 0 /* offset */) ||                    //
557
30.9k
      !CBB_add_u24_length_prefixed(cbb, body)) {
558
0
    return false;
559
0
  }
560
561
30.9k
  return true;
562
30.9k
}
563
564
30.8k
bool dtls1_finish_message(const SSL *ssl, CBB *cbb, Array<uint8_t> *out_msg) {
565
30.8k
  if (!CBBFinishArray(cbb, out_msg) ||
566
30.8k
      out_msg->size() < DTLS1_HM_HEADER_LENGTH) {
567
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
568
0
    return false;
569
0
  }
570
571
  // Fix up the header. Copy the fragment length into the total message
572
  // length.
573
30.8k
  OPENSSL_memcpy(out_msg->data() + 1,
574
30.8k
                 out_msg->data() + DTLS1_HM_HEADER_LENGTH - 3, 3);
575
30.8k
  return true;
576
30.8k
}
577
578
// add_outgoing adds a new handshake message or ChangeCipherSpec to the current
579
// outgoing flight. It returns true on success and false on error.
580
31.3k
static bool add_outgoing(SSL *ssl, bool is_ccs, Array<uint8_t> data) {
581
31.3k
  if (ssl->d1->outgoing_messages_complete) {
582
    // If we've begun writing a new flight, we received the peer flight. Discard
583
    // the timer and the our flight.
584
2.33k
    dtls1_stop_timer(ssl);
585
2.33k
    dtls_clear_outgoing_messages(ssl);
586
2.33k
  }
587
588
31.3k
  if (!is_ccs) {
589
30.7k
    if (ssl->d1->handshake_write_overflow) {
590
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
591
0
      return false;
592
0
    }
593
    // TODO(svaldez): Move this up a layer to fix abstraction for SSLTranscript
594
    // on hs.
595
30.7k
    if (ssl->s3->hs != nullptr && !ssl->s3->hs->transcript.Update(data)) {
596
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
597
0
      return false;
598
0
    }
599
30.7k
    ssl->d1->handshake_write_seq++;
600
30.7k
    if (ssl->d1->handshake_write_seq == 0) {
601
0
      ssl->d1->handshake_write_overflow = true;
602
0
    }
603
30.7k
  }
604
605
31.3k
  DTLSOutgoingMessage msg;
606
31.3k
  msg.data = std::move(data);
607
31.3k
  msg.epoch = ssl->d1->write_epoch.epoch();
608
31.3k
  msg.is_ccs = is_ccs;
609
  // Zero-length messages need 1 bit to track whether the peer has received the
610
  // message header. (Normally the message header is implicitly received when
611
  // any fragment of the message is received at all.)
612
31.3k
  if (!is_ccs && !msg.acked.Init(std::max(msg.msg_len(), size_t{1}))) {
613
0
    return false;
614
0
  }
615
616
  // This should not fail if |SSL_MAX_HANDSHAKE_FLIGHT| was sized correctly.
617
  //
618
  // TODO(crbug.com/42290594): This can currently fail in DTLS 1.3. The caller
619
  // can configure how many tickets to send, up to kMaxTickets. Additionally, if
620
  // we send 0.5-RTT tickets in 0-RTT, we may even have tickets queued up with
621
  // the server flight.
622
31.3k
  if (!ssl->d1->outgoing_messages.TryPushBack(std::move(msg))) {
623
0
    assert(false);
624
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
625
0
    return false;
626
0
  }
627
628
31.3k
  return true;
629
31.3k
}
630
631
30.7k
bool dtls1_add_message(SSL *ssl, Array<uint8_t> data) {
632
30.7k
  return add_outgoing(ssl, false /* handshake */, std::move(data));
633
30.7k
}
634
635
6.01k
bool dtls1_add_change_cipher_spec(SSL *ssl) {
636
  // DTLS 1.3 disables compatibility mode, which means that DTLS 1.3 never sends
637
  // a ChangeCipherSpec message.
638
6.01k
  if (ssl_protocol_version(ssl) > TLS1_2_VERSION) {
639
5.41k
    return true;
640
5.41k
  }
641
603
  return add_outgoing(ssl, true /* ChangeCipherSpec */, Array<uint8_t>());
642
6.01k
}
643
644
// dtls1_update_mtu updates the current MTU from the BIO, ensuring it is above
645
// the minimum.
646
15.8k
static void dtls1_update_mtu(SSL *ssl) {
647
  // TODO(davidben): No consumer implements |BIO_CTRL_DGRAM_SET_MTU| and the
648
  // only |BIO_CTRL_DGRAM_QUERY_MTU| implementation could use
649
  // |SSL_set_mtu|. Does this need to be so complex?
650
15.8k
  if (ssl->d1->mtu < dtls1_min_mtu() &&
651
9.77k
      !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
652
9.77k
    long mtu = BIO_ctrl(ssl->wbio.get(), BIO_CTRL_DGRAM_QUERY_MTU, 0, nullptr);
653
9.77k
    if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
654
0
      ssl->d1->mtu = (unsigned)mtu;
655
9.77k
    } else {
656
9.77k
      ssl->d1->mtu = kDefaultMTU;
657
9.77k
      BIO_ctrl(ssl->wbio.get(), BIO_CTRL_DGRAM_SET_MTU, ssl->d1->mtu, nullptr);
658
9.77k
    }
659
9.77k
  }
660
661
  // The MTU should be above the minimum now.
662
15.8k
  assert(ssl->d1->mtu >= dtls1_min_mtu());
663
15.8k
}
664
665
enum seal_result_t {
666
  seal_error,
667
  seal_continue,
668
  seal_flush,
669
};
670
671
// seal_next_record seals one record's worth of messages to |out| and advances
672
// |ssl|'s internal state past the data that was sealed. If progress was made,
673
// it returns |seal_flush| or |seal_continue| and sets
674
// |*out_len| to the number of bytes written.
675
//
676
// If the function stopped because the next message could not be combined into
677
// this record, it returns |seal_continue| and the caller should loop again.
678
// Otherwise, it returns |seal_flush| and the packet is complete (either because
679
// there are no more messages or the packet is full).
680
static seal_result_t seal_next_record(SSL *ssl, Span<uint8_t> out,
681
39.2k
                                      size_t *out_len) {
682
39.2k
  *out_len = 0;
683
684
  // Skip any fully acked messages.
685
39.2k
  while (ssl->d1->outgoing_written < ssl->d1->outgoing_messages.size() &&
686
30.3k
         ssl->d1->outgoing_messages[ssl->d1->outgoing_written].IsFullyAcked()) {
687
0
    ssl->d1->outgoing_offset = 0;
688
0
    ssl->d1->outgoing_written++;
689
0
  }
690
691
  // There was nothing left to write.
692
39.2k
  if (ssl->d1->outgoing_written >= ssl->d1->outgoing_messages.size()) {
693
8.90k
    return seal_flush;
694
8.90k
  }
695
696
30.3k
  const auto &first_msg = ssl->d1->outgoing_messages[ssl->d1->outgoing_written];
697
30.3k
  size_t prefix_len = dtls_seal_prefix_len(ssl, first_msg.epoch);
698
30.3k
  size_t max_in_len = dtls_seal_max_input_len(ssl, first_msg.epoch, out.size());
699
30.3k
  if (max_in_len == 0) {
700
    // There is no room for a single record.
701
0
    return seal_flush;
702
0
  }
703
704
30.3k
  if (first_msg.is_ccs) {
705
974
    static const uint8_t kChangeCipherSpec[1] = {SSL3_MT_CCS};
706
974
    DTLSRecordNumber record_number;
707
974
    if (!dtls_seal_record(ssl, &record_number, out.data(), out_len, out.size(),
708
974
                          SSL3_RT_CHANGE_CIPHER_SPEC, kChangeCipherSpec,
709
974
                          sizeof(kChangeCipherSpec), first_msg.epoch)) {
710
0
      return seal_error;
711
0
    }
712
713
974
    ssl_do_msg_callback(ssl, /*is_write=*/1, SSL3_RT_CHANGE_CIPHER_SPEC,
714
974
                        kChangeCipherSpec);
715
974
    ssl->d1->outgoing_offset = 0;
716
974
    ssl->d1->outgoing_written++;
717
974
    return seal_continue;
718
974
  }
719
720
  // TODO(crbug.com/374991962): For now, only send one message per record in
721
  // epoch 0. Sending multiple is allowed and more efficient, but breaks
722
  // b/378742138.
723
29.4k
  const bool allow_multiple_messages = first_msg.epoch != 0;
724
725
  // Pack as many handshake fragments into one record as we can. We stage the
726
  // fragments in the output buffer, to be sealed in-place.
727
29.4k
  bool should_continue = false;
728
29.4k
  Span<uint8_t> fragments =
729
29.4k
      out.subspan(prefix_len, std::min(max_in_len, out.size() - prefix_len));
730
29.4k
  CBB cbb;
731
29.4k
  CBB_init_fixed(&cbb, fragments.data(), fragments.size());
732
29.4k
  DTLSSentRecord sent_record;
733
29.4k
  sent_record.first_msg = ssl->d1->outgoing_written;
734
29.4k
  sent_record.first_msg_start = ssl->d1->outgoing_offset;
735
42.5k
  while (ssl->d1->outgoing_written < ssl->d1->outgoing_messages.size()) {
736
37.9k
    const auto &msg = ssl->d1->outgoing_messages[ssl->d1->outgoing_written];
737
37.9k
    if (msg.epoch != first_msg.epoch || msg.is_ccs) {
738
      // We can only pack messages if the epoch matches. There may be more room
739
      // in the packet, so tell the caller to keep going.
740
0
      should_continue = true;
741
0
      break;
742
0
    }
743
744
    // Decode |msg|'s header.
745
37.9k
    CBS cbs(msg.data), body_cbs;
746
37.9k
    struct hm_header_st hdr;
747
37.9k
    if (!dtls1_parse_fragment(&cbs, &hdr, &body_cbs) ||  //
748
37.9k
        hdr.frag_off != 0 ||                             //
749
37.9k
        hdr.frag_len != CBS_len(&body_cbs) ||            //
750
37.9k
        hdr.msg_len != CBS_len(&body_cbs) ||             //
751
37.9k
        CBS_len(&cbs) != 0) {
752
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
753
0
      return seal_error;
754
0
    }
755
756
    // Iterate over every un-acked range in the message, if any.
757
37.9k
    Span<const uint8_t> body = body_cbs;
758
69.2k
    for (;;) {
759
69.2k
      auto range = msg.acked.NextUnmarkedRange(ssl->d1->outgoing_offset);
760
69.2k
      if (range.empty()) {
761
        // Advance to the next message.
762
31.3k
        ssl->d1->outgoing_offset = 0;
763
31.3k
        ssl->d1->outgoing_written++;
764
31.3k
        break;
765
31.3k
      }
766
767
      // Determine how much progress can be made (minimum one byte of progress).
768
37.9k
      size_t capacity = fragments.size() - CBB_len(&cbb);
769
37.9k
      if (capacity < DTLS1_HM_HEADER_LENGTH + 1) {
770
0
        goto packet_full;
771
0
      }
772
37.9k
      size_t todo = std::min(range.size(), capacity - DTLS1_HM_HEADER_LENGTH);
773
774
      // Empty messages are special-cased in ACK tracking. We act as if they
775
      // have one byte, but in reality that byte is tracking the header.
776
37.9k
      Span<const uint8_t> frag;
777
37.9k
      if (!body.empty()) {
778
36.3k
        frag = body.subspan(range.start, todo);
779
36.3k
      }
780
781
      // Assemble the fragment.
782
37.9k
      size_t frag_start = CBB_len(&cbb);
783
37.9k
      CBB child;
784
37.9k
      if (!CBB_add_u8(&cbb, hdr.type) ||                       //
785
37.9k
          !CBB_add_u24(&cbb, hdr.msg_len) ||                   //
786
37.9k
          !CBB_add_u16(&cbb, hdr.seq) ||                       //
787
37.9k
          !CBB_add_u24(&cbb, range.start) ||                   //
788
37.9k
          !CBB_add_u24_length_prefixed(&cbb, &child) ||        //
789
37.9k
          !CBB_add_bytes(&child, frag.data(), frag.size()) ||  //
790
37.9k
          !CBB_flush(&cbb)) {
791
0
        OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
792
0
        return seal_error;
793
0
      }
794
37.9k
      size_t frag_end = CBB_len(&cbb);
795
796
      // TODO(davidben): It is odd that, on output, we inform the caller of
797
      // retransmits and individual fragments, but on input we only inform the
798
      // caller of complete messages.
799
37.9k
      ssl_do_msg_callback(ssl, /*is_write=*/1, SSL3_RT_HANDSHAKE,
800
37.9k
                          fragments.subspan(frag_start, frag_end - frag_start));
801
802
37.9k
      ssl->d1->outgoing_offset = range.start + todo;
803
37.9k
      if (todo < range.size()) {
804
        // The packet was the limiting factor.
805
6.66k
        goto packet_full;
806
6.66k
      }
807
37.9k
    }
808
809
31.3k
    if (!allow_multiple_messages) {
810
18.1k
      should_continue = true;
811
18.1k
      break;
812
18.1k
    }
813
31.3k
  }
814
815
29.4k
packet_full:
816
29.4k
  sent_record.last_msg = ssl->d1->outgoing_written;
817
29.4k
  sent_record.last_msg_end = ssl->d1->outgoing_offset;
818
819
  // We could not fit anything. Don't try to make a record.
820
29.4k
  if (CBB_len(&cbb) == 0) {
821
0
    assert(!should_continue);
822
0
    return seal_flush;
823
0
  }
824
825
29.4k
  if (!dtls_seal_record(ssl, &sent_record.number, out.data(), out_len,
826
29.4k
                        out.size(), SSL3_RT_HANDSHAKE, CBB_data(&cbb),
827
29.4k
                        CBB_len(&cbb), first_msg.epoch)) {
828
0
    return seal_error;
829
0
  }
830
831
  // If DTLS 1.3 (or if the version is not yet known and it may be DTLS 1.3),
832
  // save the record number to match against ACKs later.
833
29.4k
  if (ssl->s3->version == 0 || ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
834
20.2k
    if (ssl->d1->sent_records == nullptr) {
835
10.9k
      ssl->d1->sent_records =
836
10.9k
          MakeUnique<MRUQueue<DTLSSentRecord, DTLS_MAX_ACK_BUFFER>>();
837
10.9k
      if (ssl->d1->sent_records == nullptr) {
838
0
        return seal_error;
839
0
      }
840
10.9k
    }
841
20.2k
    ssl->d1->sent_records->PushBack(sent_record);
842
20.2k
  }
843
844
29.4k
  return should_continue ? seal_continue : seal_flush;
845
29.4k
}
846
847
// seal_next_packet writes as much of the next flight as possible to |out| and
848
// advances |ssl->d1->outgoing_written| and |ssl->d1->outgoing_offset| as
849
// appropriate.
850
20.1k
static bool seal_next_packet(SSL *ssl, Span<uint8_t> out, size_t *out_len) {
851
20.1k
  size_t total = 0;
852
39.2k
  for (;;) {
853
39.2k
    size_t len;
854
39.2k
    seal_result_t ret = seal_next_record(ssl, out, &len);
855
39.2k
    switch (ret) {
856
0
      case seal_error:
857
0
        return false;
858
859
20.1k
      case seal_flush:
860
39.2k
      case seal_continue:
861
39.2k
        out = out.subspan(len);
862
39.2k
        total += len;
863
39.2k
        break;
864
39.2k
    }
865
866
39.2k
    if (ret == seal_flush) {
867
20.1k
      break;
868
20.1k
    }
869
39.2k
  }
870
871
20.1k
  *out_len = total;
872
20.1k
  return true;
873
20.1k
}
874
875
13.5k
static int send_flight(SSL *ssl) {
876
13.5k
  if (ssl->s3->write_shutdown != ssl_shutdown_none) {
877
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
878
0
    return -1;
879
0
  }
880
881
13.5k
  if (ssl->wbio == nullptr) {
882
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_BIO_NOT_SET);
883
0
    return -1;
884
0
  }
885
886
13.5k
  if (ssl->d1->num_timeouts > DTLS1_MAX_TIMEOUTS) {
887
3
    OPENSSL_PUT_ERROR(SSL, SSL_R_READ_TIMEOUT_EXPIRED);
888
3
    return -1;
889
3
  }
890
891
13.5k
  dtls1_update_mtu(ssl);
892
893
13.5k
  Array<uint8_t> packet;
894
13.5k
  if (!packet.InitForOverwrite(ssl->d1->mtu)) {
895
0
    return -1;
896
0
  }
897
898
33.6k
  while (ssl->d1->outgoing_written < ssl->d1->outgoing_messages.size()) {
899
20.1k
    uint8_t old_written = ssl->d1->outgoing_written;
900
20.1k
    uint32_t old_offset = ssl->d1->outgoing_offset;
901
902
20.1k
    size_t packet_len;
903
20.1k
    if (!seal_next_packet(ssl, Span(packet), &packet_len)) {
904
0
      return -1;
905
0
    }
906
907
20.1k
    if (packet_len == 0 &&
908
0
        ssl->d1->outgoing_written < ssl->d1->outgoing_messages.size()) {
909
      // We made no progress with the packet size available, but did not reach
910
      // the end.
911
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_MTU_TOO_SMALL);
912
0
      return false;
913
0
    }
914
915
20.1k
    if (packet_len != 0) {
916
20.1k
      int bio_ret = BIO_write(ssl->wbio.get(), packet.data(), packet_len);
917
20.1k
      if (bio_ret <= 0) {
918
        // Retry this packet the next time around.
919
0
        ssl->d1->outgoing_written = old_written;
920
0
        ssl->d1->outgoing_offset = old_offset;
921
0
        ssl->s3->rwstate = SSL_ERROR_WANT_WRITE;
922
0
        return bio_ret;
923
0
      }
924
20.1k
    }
925
20.1k
  }
926
927
13.5k
  ssl->d1->pending_flush = true;
928
13.5k
  return 1;
929
13.5k
}
930
931
15.4k
void dtls1_finish_flight(SSL *ssl) {
932
15.4k
  if (ssl->d1->outgoing_messages.empty() ||
933
13.1k
      ssl->d1->outgoing_messages_complete) {
934
2.35k
    return;  // Nothing to do.
935
2.35k
  }
936
937
13.1k
  if (ssl->d1->outgoing_messages[0].epoch <= 2) {
938
    // DTLS 1.3 handshake messages (epoch 2 and below) implicitly ACK the
939
    // previous flight, so there is no need to ACK previous records. This
940
    // clears the ACK buffer slightly earlier than the specification suggests.
941
    // See the discussion in
942
    // https://mailarchive.ietf.org/arch/msg/tls/kjJnquJOVaWxu5hUCmNzB35eqY0/
943
12.6k
    ssl->d1->records_to_ack.Clear();
944
12.6k
    ssl->d1->ack_timer.Stop();
945
12.6k
    ssl->d1->sending_ack = false;
946
12.6k
  }
947
948
13.1k
  ssl->d1->outgoing_messages_complete = true;
949
13.1k
  ssl->d1->sending_flight = true;
950
  // Stop retransmitting the previous flight. In DTLS 1.3, we'll have stopped
951
  // the timer already, but DTLS 1.2 keeps it running until the next flight is
952
  // ready.
953
13.1k
  dtls1_stop_timer(ssl);
954
13.1k
}
955
956
2.35k
void dtls1_schedule_ack(SSL *ssl) {
957
2.35k
  ssl->d1->ack_timer.Stop();
958
2.35k
  ssl->d1->sending_ack = !ssl->d1->records_to_ack.empty();
959
2.35k
}
960
961
2.35k
static int send_ack(SSL *ssl) {
962
2.35k
  assert(ssl_protocol_version(ssl) >= TLS1_3_VERSION);
963
964
  // Ensure we don't send so many ACKs that we overflow the MTU. There is a
965
  // 2-byte length prefix and each ACK is 16 bytes.
966
2.35k
  dtls1_update_mtu(ssl);
967
2.35k
  size_t max_plaintext =
968
2.35k
      dtls_seal_max_input_len(ssl, ssl->d1->write_epoch.epoch(), ssl->d1->mtu);
969
2.35k
  if (max_plaintext < 2 + 16) {
970
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_MTU_TOO_SMALL);  // No room for even one ACK.
971
0
    return -1;
972
0
  }
973
2.35k
  size_t num_acks =
974
2.35k
      std::min((max_plaintext - 2) / 16, ssl->d1->records_to_ack.size());
975
976
  // Assemble the ACK. RFC 9147 says to sort ACKs numerically. It is unclear if
977
  // other implementations do this, but go ahead and sort for now. See
978
  // https://mailarchive.ietf.org/arch/msg/tls/kjJnquJOVaWxu5hUCmNzB35eqY0/.
979
  // Remove this if rfc9147bis removes this requirement.
980
2.35k
  InplaceVector<DTLSRecordNumber, DTLS_MAX_ACK_BUFFER> sorted;
981
2.35k
  for (size_t i = ssl->d1->records_to_ack.size() - num_acks;
982
28.6k
       i < ssl->d1->records_to_ack.size(); i++) {
983
26.2k
    sorted.PushBack(ssl->d1->records_to_ack[i]);
984
26.2k
  }
985
2.35k
  std::sort(sorted.begin(), sorted.end());
986
987
2.35k
  uint8_t buf[2 + 16 * DTLS_MAX_ACK_BUFFER];
988
2.35k
  CBB cbb, child;
989
2.35k
  CBB_init_fixed(&cbb, buf, sizeof(buf));
990
2.35k
  BSSL_CHECK(CBB_add_u16_length_prefixed(&cbb, &child));
991
26.2k
  for (const auto &number : sorted) {
992
26.2k
    BSSL_CHECK(CBB_add_u64(&child, number.epoch()));
993
26.2k
    BSSL_CHECK(CBB_add_u64(&child, number.sequence()));
994
26.2k
  }
995
2.35k
  BSSL_CHECK(CBB_flush(&cbb));
996
997
  // Encrypt it.
998
2.35k
  uint8_t record[DTLS1_3_RECORD_HEADER_WRITE_LENGTH + sizeof(buf) +
999
2.35k
                 1 /* record type */ + EVP_AEAD_MAX_OVERHEAD];
1000
2.35k
  size_t record_len;
1001
2.35k
  DTLSRecordNumber record_number;
1002
2.35k
  if (!dtls_seal_record(ssl, &record_number, record, &record_len,
1003
2.35k
                        sizeof(record), SSL3_RT_ACK, CBB_data(&cbb),
1004
2.35k
                        CBB_len(&cbb), ssl->d1->write_epoch.epoch())) {
1005
0
    return -1;
1006
0
  }
1007
1008
2.35k
  ssl_do_msg_callback(ssl, /*is_write=*/1, SSL3_RT_ACK, CBBAsSpan(&cbb));
1009
1010
2.35k
  int bio_ret =
1011
2.35k
      BIO_write(ssl->wbio.get(), record, static_cast<int>(record_len));
1012
2.35k
  if (bio_ret <= 0) {
1013
0
    ssl->s3->rwstate = SSL_ERROR_WANT_WRITE;
1014
0
    return bio_ret;
1015
0
  }
1016
1017
2.35k
  ssl->d1->pending_flush = true;
1018
2.35k
  return 1;
1019
2.35k
}
1020
1021
424k
int dtls1_flush(SSL *ssl) {
1022
  // Send the pending ACK, if any.
1023
424k
  if (ssl->d1->sending_ack) {
1024
2.35k
    int ret = send_ack(ssl);
1025
2.35k
    if (ret <= 0) {
1026
0
      return ret;
1027
0
    }
1028
2.35k
    ssl->d1->sending_ack = false;
1029
2.35k
  }
1030
1031
  // Send the pending flight, if any.
1032
424k
  if (ssl->d1->sending_flight) {
1033
13.5k
    int ret = send_flight(ssl);
1034
13.5k
    if (ret <= 0) {
1035
3
      return ret;
1036
3
    }
1037
1038
    // Reset state for the next send.
1039
13.5k
    ssl->d1->outgoing_written = 0;
1040
13.5k
    ssl->d1->outgoing_offset = 0;
1041
13.5k
    ssl->d1->sending_flight = false;
1042
1043
    // Schedule the next retransmit timer. In DTLS 1.3, we retransmit all
1044
    // flights until ACKed. In DTLS 1.2, the final Finished flight is never
1045
    // ACKed, so we do not keep the timer running after the handshake.
1046
13.5k
    if (SSL_in_init(ssl) || ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1047
13.1k
      if (ssl->d1->num_timeouts == 0) {
1048
13.1k
        ssl->d1->timeout_duration_ms = ssl->initial_timeout_duration_ms;
1049
13.1k
      } else {
1050
0
        ssl->d1->timeout_duration_ms =
1051
0
            std::min(ssl->d1->timeout_duration_ms * 2, uint32_t{60000});
1052
0
      }
1053
1054
13.1k
      OPENSSL_timeval now = ssl_ctx_get_current_time(ssl->ctx.get());
1055
13.1k
      ssl->d1->retransmit_timer.StartMicroseconds(
1056
13.1k
          now, uint64_t{ssl->d1->timeout_duration_ms} * 1000);
1057
13.1k
    }
1058
13.5k
  }
1059
1060
424k
  if (ssl->d1->pending_flush) {
1061
15.8k
    if (BIO_flush(ssl->wbio.get()) <= 0) {
1062
0
      ssl->s3->rwstate = SSL_ERROR_WANT_WRITE;
1063
0
      return -1;
1064
0
    }
1065
15.8k
    ssl->d1->pending_flush = false;
1066
15.8k
  }
1067
1068
424k
  return 1;
1069
424k
}
1070
1071
41.5k
unsigned int dtls1_min_mtu() { return kMinMTU; }
1072
1073
BSSL_NAMESPACE_END