xref: /aosp_15_r20/external/webrtc/net/dcsctp/packet/error_cause/stale_cookie_error_cause.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2021 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 #include "net/dcsctp/packet/error_cause/stale_cookie_error_cause.h"
11 
12 #include <stdint.h>
13 
14 #include <string>
15 #include <type_traits>
16 #include <vector>
17 
18 #include "absl/types/optional.h"
19 #include "api/array_view.h"
20 #include "net/dcsctp/packet/bounded_byte_reader.h"
21 #include "net/dcsctp/packet/bounded_byte_writer.h"
22 #include "net/dcsctp/packet/tlv_trait.h"
23 #include "rtc_base/strings/string_builder.h"
24 
25 namespace dcsctp {
26 
27 // https://tools.ietf.org/html/rfc4960#section-3.3.10.3
28 
29 //  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
30 //  |     Cause Code=3              |       Cause Length=8          |
31 //  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
32 //  |                 Measure of Staleness (usec.)                  |
33 //  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
34 constexpr int StaleCookieErrorCause::kType;
35 
Parse(rtc::ArrayView<const uint8_t> data)36 absl::optional<StaleCookieErrorCause> StaleCookieErrorCause::Parse(
37     rtc::ArrayView<const uint8_t> data) {
38   absl::optional<BoundedByteReader<kHeaderSize>> reader = ParseTLV(data);
39   if (!reader.has_value()) {
40     return absl::nullopt;
41   }
42   uint32_t staleness_us = reader->Load32<4>();
43   return StaleCookieErrorCause(staleness_us);
44 }
45 
SerializeTo(std::vector<uint8_t> & out) const46 void StaleCookieErrorCause::SerializeTo(std::vector<uint8_t>& out) const {
47   BoundedByteWriter<kHeaderSize> writer = AllocateTLV(out);
48   writer.Store32<4>(staleness_us_);
49 }
50 
ToString() const51 std::string StaleCookieErrorCause::ToString() const {
52   rtc::StringBuilder sb;
53   sb << "Stale Cookie Error, staleness_us=" << staleness_us_;
54   return sb.Release();
55 }
56 
57 }  // namespace dcsctp
58