• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright 2004 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 
11 #ifndef API_TRANSPORT_STUN_H_
12 #define API_TRANSPORT_STUN_H_
13 
14 // This file contains classes for dealing with the STUN protocol, as specified
15 // in RFC 5389, and its descendants.
16 
17 #include <stddef.h>
18 #include <stdint.h>
19 
20 #include <functional>
21 #include <memory>
22 #include <string>
23 #include <vector>
24 
25 #include "absl/strings/string_view.h"
26 #include "api/array_view.h"
27 #include "rtc_base/byte_buffer.h"
28 #include "rtc_base/ip_address.h"
29 #include "rtc_base/socket_address.h"
30 
31 namespace cricket {
32 
33 // These are the types of STUN messages defined in RFC 5389.
34 enum StunMessageType : uint16_t {
35   STUN_INVALID_MESSAGE_TYPE = 0x0000,
36   STUN_BINDING_REQUEST = 0x0001,
37   STUN_BINDING_INDICATION = 0x0011,
38   STUN_BINDING_RESPONSE = 0x0101,
39   STUN_BINDING_ERROR_RESPONSE = 0x0111,
40 
41   // Method 0x80, GOOG-PING is a variant of STUN BINDING
42   // that is sent instead of a STUN BINDING if the binding
43   // was identical to the one before.
44   GOOG_PING_REQUEST = 0x200,
45   GOOG_PING_RESPONSE = 0x300,
46   GOOG_PING_ERROR_RESPONSE = 0x310,
47 };
48 
49 // These are all known STUN attributes, defined in RFC 5389 and elsewhere.
50 // Next to each is the name of the class (T is StunTAttribute) that implements
51 // that type.
52 // RETRANSMIT_COUNT is the number of outstanding pings without a response at
53 // the time the packet is generated.
54 enum StunAttributeType {
55   STUN_ATTR_MAPPED_ADDRESS = 0x0001,      // Address
56   STUN_ATTR_USERNAME = 0x0006,            // ByteString
57   STUN_ATTR_MESSAGE_INTEGRITY = 0x0008,   // ByteString, 20 bytes
58   STUN_ATTR_ERROR_CODE = 0x0009,          // ErrorCode
59   STUN_ATTR_UNKNOWN_ATTRIBUTES = 0x000a,  // UInt16List
60   STUN_ATTR_REALM = 0x0014,               // ByteString
61   STUN_ATTR_NONCE = 0x0015,               // ByteString
62   STUN_ATTR_XOR_MAPPED_ADDRESS = 0x0020,  // XorAddress
63   STUN_ATTR_SOFTWARE = 0x8022,            // ByteString
64   STUN_ATTR_ALTERNATE_SERVER = 0x8023,    // Address
65   STUN_ATTR_FINGERPRINT = 0x8028,         // UInt32
66   STUN_ATTR_RETRANSMIT_COUNT = 0xFF00     // UInt32
67 };
68 
69 // These are the types of the values associated with the attributes above.
70 // This allows us to perform some basic validation when reading or adding
71 // attributes. Note that these values are for our own use, and not defined in
72 // RFC 5389.
73 enum StunAttributeValueType {
74   STUN_VALUE_UNKNOWN = 0,
75   STUN_VALUE_ADDRESS = 1,
76   STUN_VALUE_XOR_ADDRESS = 2,
77   STUN_VALUE_UINT32 = 3,
78   STUN_VALUE_UINT64 = 4,
79   STUN_VALUE_BYTE_STRING = 5,
80   STUN_VALUE_ERROR_CODE = 6,
81   STUN_VALUE_UINT16_LIST = 7
82 };
83 
84 // These are the types of STUN addresses defined in RFC 5389.
85 enum StunAddressFamily {
86   // NB: UNDEF is not part of the STUN spec.
87   STUN_ADDRESS_UNDEF = 0,
88   STUN_ADDRESS_IPV4 = 1,
89   STUN_ADDRESS_IPV6 = 2
90 };
91 
92 // These are the types of STUN error codes defined in RFC 5389.
93 enum StunErrorCode {
94   STUN_ERROR_TRY_ALTERNATE = 300,
95   STUN_ERROR_BAD_REQUEST = 400,
96   STUN_ERROR_UNAUTHORIZED = 401,
97   STUN_ERROR_UNKNOWN_ATTRIBUTE = 420,
98   STUN_ERROR_STALE_NONCE = 438,
99   STUN_ERROR_SERVER_ERROR = 500,
100   STUN_ERROR_GLOBAL_FAILURE = 600
101 };
102 
103 // Strings for the error codes above.
104 extern const char STUN_ERROR_REASON_TRY_ALTERNATE_SERVER[];
105 extern const char STUN_ERROR_REASON_BAD_REQUEST[];
106 extern const char STUN_ERROR_REASON_UNAUTHORIZED[];
107 extern const char STUN_ERROR_REASON_UNKNOWN_ATTRIBUTE[];
108 extern const char STUN_ERROR_REASON_STALE_NONCE[];
109 extern const char STUN_ERROR_REASON_SERVER_ERROR[];
110 
111 // The mask used to determine whether a STUN message is a request/response etc.
112 const uint32_t kStunTypeMask = 0x0110;
113 
114 // STUN Attribute header length.
115 const size_t kStunAttributeHeaderSize = 4;
116 
117 // Following values correspond to RFC5389.
118 const size_t kStunHeaderSize = 20;
119 const size_t kStunTransactionIdOffset = 8;
120 const size_t kStunTransactionIdLength = 12;
121 const uint32_t kStunMagicCookie = 0x2112A442;
122 constexpr size_t kStunMagicCookieLength = sizeof(kStunMagicCookie);
123 
124 // Following value corresponds to an earlier version of STUN from
125 // RFC3489.
126 const size_t kStunLegacyTransactionIdLength = 16;
127 
128 // STUN Message Integrity HMAC length.
129 const size_t kStunMessageIntegritySize = 20;
130 // Size of STUN_ATTR_MESSAGE_INTEGRITY_32
131 const size_t kStunMessageIntegrity32Size = 4;
132 
133 class StunAddressAttribute;
134 class StunAttribute;
135 class StunByteStringAttribute;
136 class StunErrorCodeAttribute;
137 class StunUInt16ListAttribute;
138 class StunUInt32Attribute;
139 class StunUInt64Attribute;
140 class StunXorAddressAttribute;
141 
142 // Records a complete STUN/TURN message.  Each message consists of a type and
143 // any number of attributes.  Each attribute is parsed into an instance of an
144 // appropriate class (see above).  The Get* methods will return instances of
145 // that attribute class.
146 class StunMessage {
147  public:
148   // Constructs a StunMessage with an invalid type and empty, legacy length
149   // (16 bytes, RFC3489) transaction id.
150   StunMessage();
151 
152   // Construct a `StunMessage` with a specific type and generate a new
153   // 12 byte transaction id (RFC5389).
154   explicit StunMessage(uint16_t type);
155 
156   StunMessage(uint16_t type, absl::string_view transaction_id);
157 
158   virtual ~StunMessage();
159 
160   // The verification status of the message. This is checked on parsing,
161   // or set by AddMessageIntegrity.
162   // These values are persisted to logs. Entries should not be renumbered and
163   // numeric values should never be reused.
164   enum class IntegrityStatus {
165     kNotSet = 0,
166     kNoIntegrity = 1,   // Message-integrity attribute missing
167     kIntegrityOk = 2,   // Message-integrity checked OK
168     kIntegrityBad = 3,  // Message-integrity verification failed
169     kMaxValue = kIntegrityBad,
170   };
171 
type()172   int type() const { return type_; }
length()173   size_t length() const { return length_; }
transaction_id()174   const std::string& transaction_id() const { return transaction_id_; }
reduced_transaction_id()175   uint32_t reduced_transaction_id() const { return reduced_transaction_id_; }
176 
177   // Returns true if the message confirms to RFC3489 rather than
178   // RFC5389. The main difference between the two versions of the STUN
179   // protocol is the presence of the magic cookie and different length
180   // of transaction ID. For outgoing packets the version of the protocol
181   // is determined by the lengths of the transaction ID.
182   bool IsLegacy() const;
183 
SetType(int type)184   [[deprecated]] void SetType(int type) { type_ = static_cast<uint16_t>(type); }
SetTransactionID(absl::string_view transaction_id)185   [[deprecated]] bool SetTransactionID(absl::string_view transaction_id) {
186     if (!IsValidTransactionId(transaction_id))
187       return false;
188     SetTransactionIdForTesting(transaction_id);
189     return true;
190   }
191 
192   // Get a list of all of the attribute types in the "comprehension required"
193   // range that were not recognized.
194   std::vector<uint16_t> GetNonComprehendedAttributes() const;
195 
196   // Gets the desired attribute value, or NULL if no such attribute type exists.
197   const StunAddressAttribute* GetAddress(int type) const;
198   const StunUInt32Attribute* GetUInt32(int type) const;
199   const StunUInt64Attribute* GetUInt64(int type) const;
200   const StunByteStringAttribute* GetByteString(int type) const;
201   const StunUInt16ListAttribute* GetUInt16List(int type) const;
202 
203   // Gets these specific attribute values.
204   const StunErrorCodeAttribute* GetErrorCode() const;
205   // Returns the code inside the error code attribute, if present, and
206   // STUN_ERROR_GLOBAL_FAILURE otherwise.
207   int GetErrorCodeValue() const;
208   const StunUInt16ListAttribute* GetUnknownAttributes() const;
209 
210   // Takes ownership of the specified attribute and adds it to the message.
211   void AddAttribute(std::unique_ptr<StunAttribute> attr);
212 
213   // Remove the last occurrence of an attribute.
214   std::unique_ptr<StunAttribute> RemoveAttribute(int type);
215 
216   // Remote all attributes and releases them.
217   void ClearAttributes();
218 
219   // Validates that a STUN message has a correct MESSAGE-INTEGRITY value.
220   // This uses the buffered raw-format message stored by Read().
221   IntegrityStatus ValidateMessageIntegrity(const std::string& password);
222 
223   // Revalidates the STUN message with (possibly) a new password.
224   // Indicates that calling logic needs review - probably previous call
225   // was checking with the wrong password.
226   IntegrityStatus RevalidateMessageIntegrity(const std::string& password);
227 
228   // Returns the current integrity status of the message.
integrity()229   IntegrityStatus integrity() const { return integrity_; }
230 
231   // Shortcut for checking if integrity is verified.
IntegrityOk()232   bool IntegrityOk() const {
233     return integrity_ == IntegrityStatus::kIntegrityOk;
234   }
235 
236   // Returns the password attribute used to set or check the integrity.
237   // Can only be called after adding or checking the integrity.
password()238   std::string password() const {
239     RTC_DCHECK(integrity_ != IntegrityStatus::kNotSet);
240     return password_;
241   }
242 
243   // Adds a MESSAGE-INTEGRITY attribute that is valid for the current message.
244   bool AddMessageIntegrity(absl::string_view password);
245 
246   // Adds a STUN_ATTR_GOOG_MESSAGE_INTEGRITY_32 attribute that is valid for the
247   // current message.
248   bool AddMessageIntegrity32(absl::string_view password);
249 
250   // Verify that a buffer has stun magic cookie and one of the specified
251   // methods. Note that it does not check for the existance of FINGERPRINT.
252   static bool IsStunMethod(rtc::ArrayView<int> methods,
253                            const char* data,
254                            size_t size);
255 
256   // Verifies that a given buffer is STUN by checking for a correct FINGERPRINT.
257   static bool ValidateFingerprint(const char* data, size_t size);
258 
259   // Generates a new 12 byte (RFC5389) transaction id.
260   static std::string GenerateTransactionId();
261 
262   // Adds a FINGERPRINT attribute that is valid for the current message.
263   bool AddFingerprint();
264 
265   // Parses the STUN packet in the given buffer and records it here. The
266   // return value indicates whether this was successful.
267   bool Read(rtc::ByteBufferReader* buf);
268 
269   // Writes this object into a STUN packet. The return value indicates whether
270   // this was successful.
271   bool Write(rtc::ByteBufferWriter* buf) const;
272 
273   // Creates an empty message. Overridable by derived classes.
274   virtual StunMessage* CreateNew() const;
275 
276   // Modify the stun magic cookie used for this STUN message.
277   // This is used for testing.
278   [[deprecated]] void SetStunMagicCookie(uint32_t val);
279 
280   // Change the internal transaction id. Used only for testing.
281   void SetTransactionIdForTesting(absl::string_view transaction_id);
282 
283   // Contruct a copy of `this`.
284   std::unique_ptr<StunMessage> Clone() const;
285 
286   // Check if the attributes of this StunMessage equals those of `other`
287   // for all attributes that `attribute_type_mask` return true
288   bool EqualAttributes(const StunMessage* other,
289                        std::function<bool(int type)> attribute_type_mask) const;
290 
291   // Validates that a STUN message in byte buffer form
292   // has a correct MESSAGE-INTEGRITY value.
293   // These functions are not recommended and will be deprecated; use
294   // ValidateMessageIntegrity(password) on the parsed form instead.
295   [[deprecated("Use member function")]] static bool ValidateMessageIntegrity(
296       const char* data,
297       size_t size,
298       const std::string& password);
299   [[deprecated("Use member function")]] static bool ValidateMessageIntegrity32(
300       const char* data,
301       size_t size,
302       const std::string& password);
303 
304   // Expose raw-buffer ValidateMessageIntegrity function for testing.
305   static bool ValidateMessageIntegrityForTesting(const char* data,
306                                                  size_t size,
307                                                  const std::string& password);
308   // Expose raw-buffer ValidateMessageIntegrity function for testing.
309   static bool ValidateMessageIntegrity32ForTesting(const char* data,
310                                                    size_t size,
311                                                    const std::string& password);
312 
313  protected:
314   // Verifies that the given attribute is allowed for this message.
315   virtual StunAttributeValueType GetAttributeValueType(int type) const;
316 
317   std::vector<std::unique_ptr<StunAttribute>> attrs_;
318 
319  private:
320   StunAttribute* CreateAttribute(int type, size_t length) /* const*/;
321   const StunAttribute* GetAttribute(int type) const;
322   static bool IsValidTransactionId(absl::string_view transaction_id);
323   bool AddMessageIntegrityOfType(int mi_attr_type,
324                                  size_t mi_attr_size,
325                                  absl::string_view key);
326   static bool ValidateMessageIntegrityOfType(int mi_attr_type,
327                                              size_t mi_attr_size,
328                                              const char* data,
329                                              size_t size,
330                                              const std::string& password);
331 
332   uint16_t type_ = STUN_INVALID_MESSAGE_TYPE;
333   uint16_t length_ = 0;
334   std::string transaction_id_;
335   uint32_t reduced_transaction_id_ = 0;
336   uint32_t stun_magic_cookie_ = kStunMagicCookie;
337   // The original buffer for messages created by Read().
338   std::string buffer_;
339   IntegrityStatus integrity_ = IntegrityStatus::kNotSet;
340   std::string password_;
341 };
342 
343 // Base class for all STUN/TURN attributes.
344 class StunAttribute {
345  public:
~StunAttribute()346   virtual ~StunAttribute() {}
347 
type()348   int type() const { return type_; }
length()349   size_t length() const { return length_; }
350 
351   // Return the type of this attribute.
352   virtual StunAttributeValueType value_type() const = 0;
353 
354   // Only XorAddressAttribute needs this so far.
SetOwner(StunMessage * owner)355   virtual void SetOwner(StunMessage* owner) {}
356 
357   // Reads the body (not the type or length) for this type of attribute from
358   // the given buffer.  Return value is true if successful.
359   virtual bool Read(rtc::ByteBufferReader* buf) = 0;
360 
361   // Writes the body (not the type or length) to the given buffer.  Return
362   // value is true if successful.
363   virtual bool Write(rtc::ByteBufferWriter* buf) const = 0;
364 
365   // Creates an attribute object with the given type and smallest length.
366   static StunAttribute* Create(StunAttributeValueType value_type,
367                                uint16_t type,
368                                uint16_t length,
369                                StunMessage* owner);
370   // TODO(?): Allow these create functions to take parameters, to reduce
371   // the amount of work callers need to do to initialize attributes.
372   static std::unique_ptr<StunAddressAttribute> CreateAddress(uint16_t type);
373   static std::unique_ptr<StunXorAddressAttribute> CreateXorAddress(
374       uint16_t type);
375   static std::unique_ptr<StunUInt32Attribute> CreateUInt32(uint16_t type);
376   static std::unique_ptr<StunUInt64Attribute> CreateUInt64(uint16_t type);
377   static std::unique_ptr<StunByteStringAttribute> CreateByteString(
378       uint16_t type);
379   static std::unique_ptr<StunUInt16ListAttribute> CreateUInt16ListAttribute(
380       uint16_t type);
381   static std::unique_ptr<StunErrorCodeAttribute> CreateErrorCode();
382   static std::unique_ptr<StunUInt16ListAttribute> CreateUnknownAttributes();
383 
384  protected:
385   StunAttribute(uint16_t type, uint16_t length);
SetLength(uint16_t length)386   void SetLength(uint16_t length) { length_ = length; }
387   void WritePadding(rtc::ByteBufferWriter* buf) const;
388   void ConsumePadding(rtc::ByteBufferReader* buf) const;
389 
390  private:
391   uint16_t type_;
392   uint16_t length_;
393 };
394 
395 // Implements STUN attributes that record an Internet address.
396 class StunAddressAttribute : public StunAttribute {
397  public:
398   static const uint16_t SIZE_UNDEF = 0;
399   static const uint16_t SIZE_IP4 = 8;
400   static const uint16_t SIZE_IP6 = 20;
401   StunAddressAttribute(uint16_t type, const rtc::SocketAddress& addr);
402   StunAddressAttribute(uint16_t type, uint16_t length);
403 
404   StunAttributeValueType value_type() const override;
405 
family()406   StunAddressFamily family() const {
407     switch (address_.ipaddr().family()) {
408       case AF_INET:
409         return STUN_ADDRESS_IPV4;
410       case AF_INET6:
411         return STUN_ADDRESS_IPV6;
412     }
413     return STUN_ADDRESS_UNDEF;
414   }
415 
GetAddress()416   const rtc::SocketAddress& GetAddress() const { return address_; }
ipaddr()417   const rtc::IPAddress& ipaddr() const { return address_.ipaddr(); }
port()418   uint16_t port() const { return address_.port(); }
419 
SetAddress(const rtc::SocketAddress & addr)420   void SetAddress(const rtc::SocketAddress& addr) {
421     address_ = addr;
422     EnsureAddressLength();
423   }
SetIP(const rtc::IPAddress & ip)424   void SetIP(const rtc::IPAddress& ip) {
425     address_.SetIP(ip);
426     EnsureAddressLength();
427   }
SetPort(uint16_t port)428   void SetPort(uint16_t port) { address_.SetPort(port); }
429 
430   bool Read(rtc::ByteBufferReader* buf) override;
431   bool Write(rtc::ByteBufferWriter* buf) const override;
432 
433  private:
EnsureAddressLength()434   void EnsureAddressLength() {
435     switch (family()) {
436       case STUN_ADDRESS_IPV4: {
437         SetLength(SIZE_IP4);
438         break;
439       }
440       case STUN_ADDRESS_IPV6: {
441         SetLength(SIZE_IP6);
442         break;
443       }
444       default: {
445         SetLength(SIZE_UNDEF);
446         break;
447       }
448     }
449   }
450   rtc::SocketAddress address_;
451 };
452 
453 // Implements STUN attributes that record an Internet address. When encoded
454 // in a STUN message, the address contained in this attribute is XORed with the
455 // transaction ID of the message.
456 class StunXorAddressAttribute : public StunAddressAttribute {
457  public:
458   StunXorAddressAttribute(uint16_t type, const rtc::SocketAddress& addr);
459   StunXorAddressAttribute(uint16_t type, uint16_t length, StunMessage* owner);
460 
461   StunAttributeValueType value_type() const override;
462   void SetOwner(StunMessage* owner) override;
463   bool Read(rtc::ByteBufferReader* buf) override;
464   bool Write(rtc::ByteBufferWriter* buf) const override;
465 
466  private:
467   rtc::IPAddress GetXoredIP() const;
468   StunMessage* owner_;
469 };
470 
471 // Implements STUN attributes that record a 32-bit integer.
472 class StunUInt32Attribute : public StunAttribute {
473  public:
474   static const uint16_t SIZE = 4;
475   StunUInt32Attribute(uint16_t type, uint32_t value);
476   explicit StunUInt32Attribute(uint16_t type);
477 
478   StunAttributeValueType value_type() const override;
479 
value()480   uint32_t value() const { return bits_; }
SetValue(uint32_t bits)481   void SetValue(uint32_t bits) { bits_ = bits; }
482 
483   bool GetBit(size_t index) const;
484   void SetBit(size_t index, bool value);
485 
486   bool Read(rtc::ByteBufferReader* buf) override;
487   bool Write(rtc::ByteBufferWriter* buf) const override;
488 
489  private:
490   uint32_t bits_;
491 };
492 
493 class StunUInt64Attribute : public StunAttribute {
494  public:
495   static const uint16_t SIZE = 8;
496   StunUInt64Attribute(uint16_t type, uint64_t value);
497   explicit StunUInt64Attribute(uint16_t type);
498 
499   StunAttributeValueType value_type() const override;
500 
value()501   uint64_t value() const { return bits_; }
SetValue(uint64_t bits)502   void SetValue(uint64_t bits) { bits_ = bits; }
503 
504   bool Read(rtc::ByteBufferReader* buf) override;
505   bool Write(rtc::ByteBufferWriter* buf) const override;
506 
507  private:
508   uint64_t bits_;
509 };
510 
511 // Implements STUN attributes that record an arbitrary byte string.
512 class StunByteStringAttribute : public StunAttribute {
513  public:
514   explicit StunByteStringAttribute(uint16_t type);
515   StunByteStringAttribute(uint16_t type, absl::string_view str);
516   StunByteStringAttribute(uint16_t type, const void* bytes, size_t length);
517   StunByteStringAttribute(uint16_t type, uint16_t length);
518   ~StunByteStringAttribute() override;
519 
520   StunAttributeValueType value_type() const override;
521 
bytes()522   const char* bytes() const { return bytes_; }
string_view()523   absl::string_view string_view() const {
524     return absl::string_view(bytes_, length());
525   }
526 
GetString()527   [[deprecated]] std::string GetString() const {
528     return std::string(bytes_, length());
529   }
530 
531   void CopyBytes(const void* bytes, size_t length);
532   void CopyBytes(absl::string_view bytes);
533 
534   uint8_t GetByte(size_t index) const;
535   void SetByte(size_t index, uint8_t value);
536 
537   bool Read(rtc::ByteBufferReader* buf) override;
538   bool Write(rtc::ByteBufferWriter* buf) const override;
539 
540  private:
541   void SetBytes(char* bytes, size_t length);
542 
543   char* bytes_;
544 };
545 
546 // Implements STUN attributes that record an error code.
547 class StunErrorCodeAttribute : public StunAttribute {
548  public:
549   static const uint16_t MIN_SIZE;
550   StunErrorCodeAttribute(uint16_t type, int code, const std::string& reason);
551   StunErrorCodeAttribute(uint16_t type, uint16_t length);
552   ~StunErrorCodeAttribute() override;
553 
554   StunAttributeValueType value_type() const override;
555 
556   // The combined error and class, e.g. 0x400.
557   int code() const;
558   void SetCode(int code);
559 
560   // The individual error components.
eclass()561   int eclass() const { return class_; }
number()562   int number() const { return number_; }
reason()563   const std::string& reason() const { return reason_; }
SetClass(uint8_t eclass)564   void SetClass(uint8_t eclass) { class_ = eclass; }
SetNumber(uint8_t number)565   void SetNumber(uint8_t number) { number_ = number; }
566   void SetReason(const std::string& reason);
567 
568   bool Read(rtc::ByteBufferReader* buf) override;
569   bool Write(rtc::ByteBufferWriter* buf) const override;
570 
571  private:
572   uint8_t class_;
573   uint8_t number_;
574   std::string reason_;
575 };
576 
577 // Implements STUN attributes that record a list of attribute names.
578 class StunUInt16ListAttribute : public StunAttribute {
579  public:
580   StunUInt16ListAttribute(uint16_t type, uint16_t length);
581   ~StunUInt16ListAttribute() override;
582 
583   StunAttributeValueType value_type() const override;
584 
585   size_t Size() const;
586   uint16_t GetType(int index) const;
587   void SetType(int index, uint16_t value);
588   void AddType(uint16_t value);
589   void AddTypeAtIndex(uint16_t index, uint16_t value);
590 
591   bool Read(rtc::ByteBufferReader* buf) override;
592   bool Write(rtc::ByteBufferWriter* buf) const override;
593 
594  private:
595   std::vector<uint16_t>* attr_types_;
596 };
597 
598 // Return a string e.g "STUN BINDING request".
599 std::string StunMethodToString(int msg_type);
600 
601 // Returns the (successful) response type for the given request type.
602 // Returns -1 if `request_type` is not a valid request type.
603 int GetStunSuccessResponseType(int request_type);
604 
605 // Returns the error response type for the given request type.
606 // Returns -1 if `request_type` is not a valid request type.
607 int GetStunErrorResponseType(int request_type);
608 
609 // Returns whether a given message is a request type.
610 bool IsStunRequestType(int msg_type);
611 
612 // Returns whether a given message is an indication type.
613 bool IsStunIndicationType(int msg_type);
614 
615 // Returns whether a given response is a success type.
616 bool IsStunSuccessResponseType(int msg_type);
617 
618 // Returns whether a given response is an error type.
619 bool IsStunErrorResponseType(int msg_type);
620 
621 // Computes the STUN long-term credential hash.
622 bool ComputeStunCredentialHash(const std::string& username,
623                                const std::string& realm,
624                                const std::string& password,
625                                std::string* hash);
626 
627 // Make a copy af `attribute` and return a new StunAttribute.
628 //   This is useful if you don't care about what kind of attribute you
629 //   are handling.
630 //
631 // The implementation copies by calling Write() followed by Read().
632 //
633 // If `tmp_buffer` is supplied this buffer will be used, otherwise
634 // a buffer will created in the method.
635 std::unique_ptr<StunAttribute> CopyStunAttribute(
636     const StunAttribute& attribute,
637     rtc::ByteBufferWriter* tmp_buffer_ptr = 0);
638 
639 // TODO(?): Move the TURN/ICE stuff below out to separate files.
640 extern const char TURN_MAGIC_COOKIE_VALUE[4];
641 
642 // "GTURN" STUN methods.
643 // TODO(?): Rename these methods to GTURN_ to make it clear they aren't
644 // part of standard STUN/TURN.
645 enum RelayMessageType {
646   // For now, using the same defs from TurnMessageType below.
647   // STUN_ALLOCATE_REQUEST              = 0x0003,
648   // STUN_ALLOCATE_RESPONSE             = 0x0103,
649   // STUN_ALLOCATE_ERROR_RESPONSE       = 0x0113,
650   STUN_SEND_REQUEST = 0x0004,
651   STUN_SEND_RESPONSE = 0x0104,
652   STUN_SEND_ERROR_RESPONSE = 0x0114,
653   STUN_DATA_INDICATION = 0x0115,
654 };
655 
656 // "GTURN"-specific STUN attributes.
657 // TODO(?): Rename these attributes to GTURN_ to avoid conflicts.
658 enum RelayAttributeType {
659   STUN_ATTR_LIFETIME = 0x000d,             // UInt32
660   STUN_ATTR_MAGIC_COOKIE = 0x000f,         // ByteString, 4 bytes
661   STUN_ATTR_BANDWIDTH = 0x0010,            // UInt32
662   STUN_ATTR_DESTINATION_ADDRESS = 0x0011,  // Address
663   STUN_ATTR_SOURCE_ADDRESS2 = 0x0012,      // Address
664   STUN_ATTR_DATA = 0x0013,                 // ByteString
665   STUN_ATTR_OPTIONS = 0x8001,              // UInt32
666 };
667 
668 // A "GTURN" STUN message.
669 class RelayMessage : public StunMessage {
670  public:
671   using StunMessage::StunMessage;
672 
673  protected:
674   StunAttributeValueType GetAttributeValueType(int type) const override;
675   StunMessage* CreateNew() const override;
676 };
677 
678 // Defined in TURN RFC 5766.
679 enum TurnMessageType : uint16_t {
680   STUN_ALLOCATE_REQUEST = 0x0003,
681   STUN_ALLOCATE_RESPONSE = 0x0103,
682   STUN_ALLOCATE_ERROR_RESPONSE = 0x0113,
683   TURN_REFRESH_REQUEST = 0x0004,
684   TURN_REFRESH_RESPONSE = 0x0104,
685   TURN_REFRESH_ERROR_RESPONSE = 0x0114,
686   TURN_SEND_INDICATION = 0x0016,
687   TURN_DATA_INDICATION = 0x0017,
688   TURN_CREATE_PERMISSION_REQUEST = 0x0008,
689   TURN_CREATE_PERMISSION_RESPONSE = 0x0108,
690   TURN_CREATE_PERMISSION_ERROR_RESPONSE = 0x0118,
691   TURN_CHANNEL_BIND_REQUEST = 0x0009,
692   TURN_CHANNEL_BIND_RESPONSE = 0x0109,
693   TURN_CHANNEL_BIND_ERROR_RESPONSE = 0x0119,
694 };
695 
696 enum TurnAttributeType {
697   STUN_ATTR_CHANNEL_NUMBER = 0x000C,    // UInt32
698   STUN_ATTR_TURN_LIFETIME = 0x000d,     // UInt32
699   STUN_ATTR_XOR_PEER_ADDRESS = 0x0012,  // XorAddress
700   // TODO(mallinath) - Uncomment after RelayAttributes are renamed.
701   // STUN_ATTR_DATA                     = 0x0013,  // ByteString
702   STUN_ATTR_XOR_RELAYED_ADDRESS = 0x0016,  // XorAddress
703   STUN_ATTR_EVEN_PORT = 0x0018,            // ByteString, 1 byte.
704   STUN_ATTR_REQUESTED_TRANSPORT = 0x0019,  // UInt32
705   STUN_ATTR_DONT_FRAGMENT = 0x001A,        // No content, Length = 0
706   STUN_ATTR_RESERVATION_TOKEN = 0x0022,    // ByteString, 8 bytes.
707   // TODO(mallinath) - Rename STUN_ATTR_TURN_LIFETIME to STUN_ATTR_LIFETIME and
708   // STUN_ATTR_TURN_DATA to STUN_ATTR_DATA. Also rename RelayMessage attributes
709   // by appending G to attribute name.
710 };
711 
712 // RFC 5766-defined errors.
713 enum TurnErrorType {
714   STUN_ERROR_FORBIDDEN = 403,
715   STUN_ERROR_ALLOCATION_MISMATCH = 437,
716   STUN_ERROR_WRONG_CREDENTIALS = 441,
717   STUN_ERROR_UNSUPPORTED_PROTOCOL = 442
718 };
719 
720 extern const int SERVER_NOT_REACHABLE_ERROR;
721 
722 extern const char STUN_ERROR_REASON_FORBIDDEN[];
723 extern const char STUN_ERROR_REASON_ALLOCATION_MISMATCH[];
724 extern const char STUN_ERROR_REASON_WRONG_CREDENTIALS[];
725 extern const char STUN_ERROR_REASON_UNSUPPORTED_PROTOCOL[];
726 class TurnMessage : public StunMessage {
727  public:
728   using StunMessage::StunMessage;
729 
730  protected:
731   StunAttributeValueType GetAttributeValueType(int type) const override;
732   StunMessage* CreateNew() const override;
733 };
734 
735 enum IceAttributeType {
736   // RFC 5245 ICE STUN attributes.
737   STUN_ATTR_PRIORITY = 0x0024,         // UInt32
738   STUN_ATTR_USE_CANDIDATE = 0x0025,    // No content, Length = 0
739   STUN_ATTR_ICE_CONTROLLED = 0x8029,   // UInt64
740   STUN_ATTR_ICE_CONTROLLING = 0x802A,  // UInt64
741   // The following attributes are in the comprehension-optional range
742   // (0xC000-0xFFFF) and are not registered with IANA. These STUN attributes are
743   // intended for ICE and should NOT be used in generic use cases of STUN
744   // messages.
745   //
746   // Note that the value 0xC001 has already been assigned by IANA to
747   // ENF-FLOW-DESCRIPTION
748   // (https://www.iana.org/assignments/stun-parameters/stun-parameters.xml).
749   STUN_ATTR_NOMINATION = 0xC001,  // UInt32
750   // UInt32. The higher 16 bits are the network ID. The lower 16 bits are the
751   // network cost.
752   STUN_ATTR_GOOG_NETWORK_INFO = 0xC057,
753   // Experimental: Transaction ID of the last connectivity check received.
754   STUN_ATTR_GOOG_LAST_ICE_CHECK_RECEIVED = 0xC058,
755   // Uint16List. Miscellaneous attributes for future extension.
756   STUN_ATTR_GOOG_MISC_INFO = 0xC059,
757   // Obsolete.
758   STUN_ATTR_GOOG_OBSOLETE_1 = 0xC05A,
759   STUN_ATTR_GOOG_CONNECTION_ID = 0xC05B,  // Not yet implemented.
760   STUN_ATTR_GOOG_DELTA = 0xC05C,          // Not yet implemented.
761   STUN_ATTR_GOOG_DELTA_ACK = 0xC05D,      // Not yet implemented.
762   // MESSAGE-INTEGRITY truncated to 32-bit.
763   STUN_ATTR_GOOG_MESSAGE_INTEGRITY_32 = 0xC060,
764 };
765 
766 // When adding new attributes to STUN_ATTR_GOOG_MISC_INFO
767 // (which is a list of uint16_t), append the indices of these attributes below
768 // and do NOT change the existing indices. The indices of attributes must be
769 // consistent with those used in ConnectionRequest::Prepare when forming a STUN
770 // message for the ICE connectivity check, and they are used when parsing a
771 // received STUN message.
772 enum class IceGoogMiscInfoBindingRequestAttributeIndex {
773   SUPPORT_GOOG_PING_VERSION = 0,
774 };
775 
776 enum class IceGoogMiscInfoBindingResponseAttributeIndex {
777   SUPPORT_GOOG_PING_VERSION = 0,
778 };
779 
780 // RFC 5245-defined errors.
781 enum IceErrorCode {
782   STUN_ERROR_ROLE_CONFLICT = 487,
783 };
784 extern const char STUN_ERROR_REASON_ROLE_CONFLICT[];
785 
786 // A RFC 5245 ICE STUN message.
787 class IceMessage : public StunMessage {
788  public:
789   using StunMessage::StunMessage;
790 
791  protected:
792   StunAttributeValueType GetAttributeValueType(int type) const override;
793   StunMessage* CreateNew() const override;
794 };
795 
796 }  // namespace cricket
797 
798 #endif  // API_TRANSPORT_STUN_H_
799