1 // Copyright (c) 2012 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.
5 #ifndef CHROME_BROWSER_EXTENSIONS_API_DIAL_DIAL_SERVICE_H_
6 #define CHROME_BROWSER_EXTENSIONS_API_DIAL_DIAL_SERVICE_H_
10 #include "base/gtest_prod_util.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/memory/weak_ptr.h"
13 #include "base/observer_list.h"
14 #include "base/threading/thread_checker.h"
15 #include "base/timer/timer.h"
16 #include "net/base/net_log.h"
17 #include "net/udp/udp_socket.h"
24 struct NetworkInterface;
27 namespace extensions {
31 // DialService accepts requests to discover devices, sends multiple M-SEARCH
32 // requests via UDP multicast, and notifies observers when a DIAL-compliant
35 // Each time Discover() is called, kDialNumRequests M-SEARCH requests are sent
36 // (with a delay of kDialRequestIntervalMillis in between):
40 // T1 Request 1 sent, OnDiscoveryReqest() called
42 // Tk Request kDialNumRequests sent, OnDiscoveryReqest() called
43 // Tf OnDiscoveryFinished() called
45 // Any time a valid response is received between T1 and Tf, it is parsed and
46 // OnDeviceDiscovered() is called with the result. Tf is set to Tk +
47 // kDialResponseTimeoutSecs (the response timeout passed in each request).
49 // Calling Discover() again between T1 and Tf has no effect.
51 // All relevant constants are defined in dial_service.cc.
53 // TODO(mfoltz): Port this into net/.
54 // See https://code.google.com/p/chromium/issues/detail?id=164473
57 enum DialServiceErrorCode {
58 DIAL_SERVICE_NO_INTERFACES = 0,
59 DIAL_SERVICE_SOCKET_ERROR
64 // Called when a single discovery request was sent.
65 virtual void OnDiscoveryRequest(DialService* service) = 0;
67 // Called when a device responds to a request.
68 virtual void OnDeviceDiscovered(DialService* service,
69 const DialDeviceData& device) = 0;
71 // Called when we have all responses from the last discovery request.
72 virtual void OnDiscoveryFinished(DialService* service) = 0;
74 // Called when an error occurs.
75 virtual void OnError(DialService* service,
76 const DialServiceErrorCode& code) = 0;
79 virtual ~Observer() {}
82 virtual ~DialService() {}
84 // Starts a new round of discovery. Returns |true| if discovery was started
85 // successfully or there is already one active. Returns |false| on error.
86 virtual bool Discover() = 0;
88 // Called by listeners to this service to add/remove themselves as observers.
89 virtual void AddObserver(Observer* observer) = 0;
90 virtual void RemoveObserver(Observer* observer) = 0;
91 virtual bool HasObserver(Observer* observer) = 0;
94 // Implements DialService.
96 // NOTE(mfoltz): It would make this class cleaner to refactor most of the state
97 // associated with a single discovery cycle into its own |DiscoveryOperation|
98 // object. This would also simplify lifetime of the object w.r.t. DialRegistry;
99 // the Registry would not need to create/destroy the Service on demand.
100 class DialServiceImpl : public DialService,
101 public base::SupportsWeakPtr<DialServiceImpl> {
103 explicit DialServiceImpl(net::NetLog* net_log);
104 virtual ~DialServiceImpl();
106 // DialService implementation
107 virtual bool Discover() OVERRIDE;
108 virtual void AddObserver(Observer* observer) OVERRIDE;
109 virtual void RemoveObserver(Observer* observer) OVERRIDE;
110 virtual bool HasObserver(Observer* observer) OVERRIDE;
113 // Starts the control flow for one discovery cycle.
114 void StartDiscovery();
116 // Establishes the UDP socket that is used for requests and responses,
117 // establishes a read callback on the socket, and sends the first discovery
118 // request. Returns true if successful.
119 bool BindSocketAndSendRequest(const net::IPAddressNumber& bind_ip_address);
121 // Sends a single discovery request over the socket.
122 void SendOneRequest();
124 // Callback invoked for socket writes.
125 void OnSocketWrite(int result);
127 // Send the network list to IO thread.
128 void SendNetworkList(const net::NetworkInterfaceList& list);
130 // Establishes the callback to read from the socket. Returns true if
134 // Callback invoked for socket reads.
135 void OnSocketRead(int result);
137 // Handles |bytes_read| bytes read from the socket and calls ReadSocket to
138 // await the next response.
139 void HandleResponse(int bytes_read);
141 // Parses a response into a DialDeviceData object. If the DIAL response is
142 // invalid or does not contain enough information, then the return
143 // value will be false and |device| is not changed.
144 static bool ParseResponse(const std::string& response,
145 const base::Time& response_time,
146 DialDeviceData* device);
148 // Called from finish_timer_ when we are done with the current round of
150 void FinishDiscovery();
152 // Closes the socket.
155 // Checks the result of a socket operation. If the result is an error, closes
156 // the socket, notifies observers via OnError(), and returns |false|. Returns
158 bool CheckResult(const char* operation, int result);
161 scoped_ptr<net::UDPSocket> socket_;
163 // The multicast address:port for search requests.
164 net::IPEndPoint send_address_;
166 // The NetLog for this service.
167 net::NetLog* net_log_;
169 // The NetLog source for this service.
170 net::NetLog::Source net_log_source_;
172 // Buffer for socket writes.
173 scoped_refptr<net::StringIOBuffer> send_buffer_;
175 // Marks whether there is an active write callback.
178 // Buffer for socket reads.
179 scoped_refptr<net::IOBufferWithSize> recv_buffer_;
181 // The source of of the last socket read.
182 net::IPEndPoint recv_address_;
184 // Marks whether there is an active read callback.
187 // True when we are currently doing discovery.
188 bool discovery_active_;
190 // The number of requests that have been sent in the current discovery.
191 int num_requests_sent_;
193 // The maximum number of requests to send per discovery cycle.
196 // Timer for finishing discovery.
197 base::OneShotTimer<DialServiceImpl> finish_timer_;
199 // The delay for |finish_timer_|; how long to wait for discovery to finish.
200 // Setting this to zero disables the timer.
201 base::TimeDelta finish_delay_;
203 // Timer for sending multiple requests at fixed intervals.
204 base::RepeatingTimer<DialServiceImpl> request_timer_;
206 // The delay for |request_timer_|; how long to wait between successive
208 base::TimeDelta request_interval_;
210 // List of observers.
211 ObserverList<Observer> observer_list_;
214 base::ThreadChecker thread_checker_;
216 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestSendMultipleRequests);
217 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestOnDeviceDiscovered);
218 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestOnDiscoveryFinished);
219 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestOnDiscoveryRequest);
220 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestResponseParsing);
221 DISALLOW_COPY_AND_ASSIGN(DialServiceImpl);
224 } // namespace extensions
226 #endif // CHROME_BROWSER_EXTENSIONS_API_DIAL_DIAL_SERVICE_H_