1 /*
2  *  Copyright 2018 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 RTC_BASE_FAKE_MDNS_RESPONDER_H_
12 #define RTC_BASE_FAKE_MDNS_RESPONDER_H_
13 
14 #include <map>
15 #include <memory>
16 #include <string>
17 
18 #include "rtc_base/async_invoker.h"
19 #include "rtc_base/ip_address.h"
20 #include "rtc_base/location.h"
21 #include "rtc_base/mdns_responder_interface.h"
22 #include "rtc_base/thread.h"
23 
24 namespace webrtc {
25 
26 class FakeMdnsResponder : public MdnsResponderInterface {
27  public:
FakeMdnsResponder(rtc::Thread * thread)28   explicit FakeMdnsResponder(rtc::Thread* thread) : thread_(thread) {}
29   ~FakeMdnsResponder() = default;
30 
CreateNameForAddress(const rtc::IPAddress & addr,NameCreatedCallback callback)31   void CreateNameForAddress(const rtc::IPAddress& addr,
32                             NameCreatedCallback callback) override {
33     std::string name;
34     if (addr_name_map_.find(addr) != addr_name_map_.end()) {
35       name = addr_name_map_[addr];
36     } else {
37       name = std::to_string(next_available_id_++) + ".local";
38       addr_name_map_[addr] = name;
39     }
40     invoker_.AsyncInvoke<void>(
41         RTC_FROM_HERE, thread_,
42         [callback, addr, name]() { callback(addr, name); });
43   }
RemoveNameForAddress(const rtc::IPAddress & addr,NameRemovedCallback callback)44   void RemoveNameForAddress(const rtc::IPAddress& addr,
45                             NameRemovedCallback callback) override {
46     auto it = addr_name_map_.find(addr);
47     if (it != addr_name_map_.end()) {
48       addr_name_map_.erase(it);
49     }
50     bool result = it != addr_name_map_.end();
51     invoker_.AsyncInvoke<void>(RTC_FROM_HERE, thread_,
52                                [callback, result]() { callback(result); });
53   }
54 
GetMappedAddressForName(const std::string & name)55   rtc::IPAddress GetMappedAddressForName(const std::string& name) const {
56     for (const auto& addr_name_pair : addr_name_map_) {
57       if (addr_name_pair.second == name) {
58         return addr_name_pair.first;
59       }
60     }
61     return rtc::IPAddress();
62   }
63 
64  private:
65   uint32_t next_available_id_ = 0;
66   std::map<rtc::IPAddress, std::string> addr_name_map_;
67   rtc::Thread* thread_;
68   rtc::AsyncInvoker invoker_;
69 };
70 
71 }  // namespace webrtc
72 
73 #endif  // RTC_BASE_FAKE_MDNS_RESPONDER_H_
74