xref: /aosp_15_r20/external/webrtc/p2p/base/stun_server.h (revision d9f758449e529ab9291ac668be2861e7a55c2422)
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 P2P_BASE_STUN_SERVER_H_
12 #define P2P_BASE_STUN_SERVER_H_
13 
14 #include <stddef.h>
15 #include <stdint.h>
16 
17 #include <memory>
18 
19 #include "absl/strings/string_view.h"
20 #include "api/transport/stun.h"
21 #include "rtc_base/async_packet_socket.h"
22 #include "rtc_base/async_udp_socket.h"
23 #include "rtc_base/socket_address.h"
24 #include "rtc_base/third_party/sigslot/sigslot.h"
25 
26 namespace cricket {
27 
28 const int STUN_SERVER_PORT = 3478;
29 
30 class StunServer : public sigslot::has_slots<> {
31  public:
32   // Creates a STUN server, which will listen on the given socket.
33   explicit StunServer(rtc::AsyncUDPSocket* socket);
34   // Removes the STUN server from the socket and deletes the socket.
35   ~StunServer() override;
36 
37  protected:
38   // Slot for Socket.PacketRead:
39   void OnPacket(rtc::AsyncPacketSocket* socket,
40                 const char* buf,
41                 size_t size,
42                 const rtc::SocketAddress& remote_addr,
43                 const int64_t& packet_time_us);
44 
45   // Handlers for the different types of STUN/TURN requests:
46   virtual void OnBindingRequest(StunMessage* msg,
47                                 const rtc::SocketAddress& addr);
48   void OnAllocateRequest(StunMessage* msg, const rtc::SocketAddress& addr);
49   void OnSharedSecretRequest(StunMessage* msg, const rtc::SocketAddress& addr);
50   void OnSendRequest(StunMessage* msg, const rtc::SocketAddress& addr);
51 
52   // Sends an error response to the given message back to the user.
53   void SendErrorResponse(const StunMessage& msg,
54                          const rtc::SocketAddress& addr,
55                          int error_code,
56                          absl::string_view error_desc);
57 
58   // Sends the given message to the appropriate destination.
59   void SendResponse(const StunMessage& msg, const rtc::SocketAddress& addr);
60 
61   // A helper method to compose a STUN binding response.
62   void GetStunBindResponse(StunMessage* message,
63                            const rtc::SocketAddress& remote_addr,
64                            StunMessage* response) const;
65 
66  private:
67   std::unique_ptr<rtc::AsyncUDPSocket> socket_;
68 };
69 
70 }  // namespace cricket
71 
72 #endif  // P2P_BASE_STUN_SERVER_H_
73