Home | History | Annotate | Download | only in base
      1 /*
      2  *  Copyright 2008 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 WEBRTC_P2P_BASE_TESTSTUNSERVER_H_
     12 #define WEBRTC_P2P_BASE_TESTSTUNSERVER_H_
     13 
     14 #include "webrtc/p2p/base/stunserver.h"
     15 #include "webrtc/base/socketaddress.h"
     16 #include "webrtc/base/thread.h"
     17 
     18 namespace cricket {
     19 
     20 // A test STUN server. Useful for unit tests.
     21 class TestStunServer : StunServer {
     22  public:
     23   static TestStunServer* Create(rtc::Thread* thread,
     24                                 const rtc::SocketAddress& addr) {
     25     rtc::AsyncSocket* socket =
     26         thread->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
     27     rtc::AsyncUDPSocket* udp_socket =
     28         rtc::AsyncUDPSocket::Create(socket, addr);
     29 
     30     return new TestStunServer(udp_socket);
     31   }
     32 
     33   // Set a fake STUN address to return to the client.
     34   void set_fake_stun_addr(const rtc::SocketAddress& addr) {
     35     fake_stun_addr_ = addr;
     36   }
     37 
     38  private:
     39   explicit TestStunServer(rtc::AsyncUDPSocket* socket) : StunServer(socket) {}
     40 
     41   void OnBindingRequest(StunMessage* msg,
     42                         const rtc::SocketAddress& remote_addr) override {
     43     if (fake_stun_addr_.IsNil()) {
     44       StunServer::OnBindingRequest(msg, remote_addr);
     45     } else {
     46       StunMessage response;
     47       GetStunBindReqponse(msg, fake_stun_addr_, &response);
     48       SendResponse(response, remote_addr);
     49     }
     50   }
     51 
     52  private:
     53   rtc::SocketAddress fake_stun_addr_;
     54 };
     55 
     56 }  // namespace cricket
     57 
     58 #endif  // WEBRTC_P2P_BASE_TESTSTUNSERVER_H_
     59