summaryrefslogtreecommitdiffstats
path: root/chrome/browser/local_discovery/privet_traffic_detector.h
blob: f1a64d032d617359e1bb0c73c5b73740f68df033 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CHROME_BROWSER_LOCAL_DISCOVERY_PRIVET_TRAFFIC_DETECTOR_H_
#define CHROME_BROWSER_LOCAL_DISCOVERY_PRIVET_TRAFFIC_DETECTOR_H_

#include "base/callback.h"
#include "base/cancelable_callback.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/address_family.h"
#include "net/base/ip_endpoint.h"
#include "net/base/network_change_notifier.h"

namespace net {
class DatagramServerSocket;
class IOBufferWithSize;
}

namespace local_discovery {

// Detects mDns traffic that looks like "Privet" protocol.
// Can produce false positives results, but main task of the class is to avoid
// running full mDns listener if user doesn't have devices.
// When traffic is detected, class fires callback and shutdowns itself.
class PrivetTrafficDetector
    : public base::RefCountedThreadSafe<
          PrivetTrafficDetector, content::BrowserThread::DeleteOnIOThread>,
      private net::NetworkChangeNotifier::NetworkChangeObserver {
 public:
  PrivetTrafficDetector(net::AddressFamily address_family,
                        const base::Closure& on_traffic_detected);

  void Start();

 private:
  friend struct content::BrowserThread::DeleteOnThread<
      content::BrowserThread::IO>;
  friend class base::DeleteHelper<PrivetTrafficDetector>;
  ~PrivetTrafficDetector() override;

    // net::NetworkChangeNotifier::NetworkChangeObserver implementation.
  void OnNetworkChanged(
      net::NetworkChangeNotifier::ConnectionType type) override;

  void StartOnIOThread();
  void ScheduleRestart();
  void Restart(const net::NetworkInterfaceList& networks);
  int Bind();
  bool IsSourceAcceptable() const;
  bool IsPrivetPacket(int rv) const;
  int DoLoop(int rv);

  base::Closure on_traffic_detected_;
  scoped_refptr<base::TaskRunner> callback_runner_;
  net::NetworkInterfaceList networks_;
  net::AddressFamily address_family_;
  net::IPEndPoint recv_addr_;
  scoped_ptr<net::DatagramServerSocket> socket_;
  scoped_refptr<net::IOBufferWithSize> io_buffer_;
  base::Time start_time_;
  int restart_attempts_;

  base::WeakPtrFactory<PrivetTrafficDetector> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(PrivetTrafficDetector);
};

}  // namespace local_discovery

#endif  // CHROME_BROWSER_LOCAL_DISCOVERY_PRIVET_TRAFFIC_DETECTOR_H_