• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef DISCOVERY_MDNS_MDNS_RECEIVER_H_
6 #define DISCOVERY_MDNS_MDNS_RECEIVER_H_
7 
8 #include <functional>
9 
10 #include "discovery/common/config.h"
11 #include "platform/api/udp_socket.h"
12 #include "platform/base/error.h"
13 #include "platform/base/udp_packet.h"
14 
15 namespace openscreen {
16 namespace discovery {
17 
18 class MdnsMessage;
19 
20 class MdnsReceiver {
21  public:
22   class ResponseClient {
23    public:
24     virtual ~ResponseClient();
25 
26     virtual void OnMessageReceived(const MdnsMessage& message) = 0;
27   };
28 
29   // MdnsReceiver does not own |socket| and |delegate|
30   // and expects that the lifetime of these objects exceeds the lifetime of
31   // MdnsReceiver.
32   explicit MdnsReceiver(Config config);
33   MdnsReceiver(const MdnsReceiver& other) = delete;
34   MdnsReceiver(MdnsReceiver&& other) noexcept = delete;
35   MdnsReceiver& operator=(const MdnsReceiver& other) = delete;
36   MdnsReceiver& operator=(MdnsReceiver&& other) noexcept = delete;
37   ~MdnsReceiver();
38 
39   void SetQueryCallback(
40       std::function<void(const MdnsMessage&, const IPEndpoint& src)> callback);
41   void AddResponseCallback(ResponseClient* callback);
42   void RemoveResponseCallback(ResponseClient* callback);
43 
44   // The receiver can be started and stopped multiple times.
45   // Start and Stop are both synchronous calls. When MdnsReceiver has not yet
46   // been started, OnRead callbacks it receives from the task runner will be
47   // no-ops.
48   void Start();
49   void Stop();
50 
51   void OnRead(UdpSocket* socket, ErrorOr<UdpPacket> packet);
52 
53  private:
54   enum class State {
55     kStopped,
56     kRunning,
57   };
58 
59   std::function<void(const MdnsMessage&, const IPEndpoint& src)>
60       query_callback_;
61   State state_ = State::kStopped;
62 
63   std::vector<ResponseClient*> response_clients_;
64 
65   Config config_;
66 };
67 
68 }  // namespace discovery
69 }  // namespace openscreen
70 
71 #endif  // DISCOVERY_MDNS_MDNS_RECEIVER_H_
72