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