Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(361)

Side by Side Diff: chrome/browser/extensions/api/dial/dial_service.h

Issue 2756483007: [Device Discovery] Move files from browser/extensions/api/dial to browser/media/router/discovery/di… (Closed)
Patch Set: resolve code review comments from Devlin Created 3 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
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.
4
5 #ifndef CHROME_BROWSER_EXTENSIONS_API_DIAL_DIAL_SERVICE_H_
6 #define CHROME_BROWSER_EXTENSIONS_API_DIAL_DIAL_SERVICE_H_
7
8 #include <memory>
9 #include <string>
10 #include <vector>
11
12 #include "base/gtest_prod_util.h"
13 #include "base/macros.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/observer_list.h"
16 #include "base/timer/timer.h"
17 #include "net/base/ip_address.h"
18 #include "net/log/net_log_source.h"
19 #include "net/socket/udp_socket.h"
20
21 namespace net {
22 class IPEndPoint;
23 class StringIOBuffer;
24 class NetLog;
25 }
26
27 namespace extensions {
28 namespace api {
29 namespace dial {
30
31 class DialDeviceData;
32
33 // DialService accepts requests to discover devices, sends multiple M-SEARCH
34 // requests via UDP multicast, and notifies observers when a DIAL-compliant
35 // device responds.
36 //
37 // Each time Discover() is called, kDialNumRequests M-SEARCH requests are sent
38 // (with a delay of kDialRequestIntervalMillis in between):
39 //
40 // Time Action
41 // ---- ------
42 // T1 Request 1 sent, OnDiscoveryReqest() called
43 // ...
44 // Tk Request kDialNumRequests sent, OnDiscoveryReqest() called
45 // Tf OnDiscoveryFinished() called
46 //
47 // Any time a valid response is received between T1 and Tf, it is parsed and
48 // OnDeviceDiscovered() is called with the result. Tf is set to Tk +
49 // kDialResponseTimeoutSecs (the response timeout passed in each request).
50 //
51 // Calling Discover() again between T1 and Tf has no effect.
52 //
53 // All relevant constants are defined in dial_service.cc.
54 class DialService {
55 public:
56 enum DialServiceErrorCode {
57 DIAL_SERVICE_NO_INTERFACES = 0,
58 DIAL_SERVICE_SOCKET_ERROR
59 };
60
61 class Observer {
62 public:
63 // Called when a single discovery request was sent.
64 virtual void OnDiscoveryRequest(DialService* service) = 0;
65
66 // Called when a device responds to a request.
67 virtual void OnDeviceDiscovered(DialService* service,
68 const DialDeviceData& device) = 0;
69
70 // Called when we have all responses from the last discovery request.
71 virtual void OnDiscoveryFinished(DialService* service) = 0;
72
73 // Called when an error occurs.
74 virtual void OnError(DialService* service,
75 const DialServiceErrorCode& code) = 0;
76
77 protected:
78 virtual ~Observer() {}
79 };
80
81 virtual ~DialService() {}
82
83 // Starts a new round of discovery. Returns |true| if discovery was started
84 // successfully or there is already one active. Returns |false| on error.
85 virtual bool Discover() = 0;
86
87 // Called by listeners to this service to add/remove themselves as observers.
88 virtual void AddObserver(Observer* observer) = 0;
89 virtual void RemoveObserver(Observer* observer) = 0;
90 virtual bool HasObserver(const Observer* observer) const = 0;
91 };
92
93 // Implements DialService.
94 //
95 // NOTE(mfoltz): It would make this class cleaner to refactor most of the state
96 // associated with a single discovery cycle into its own |DiscoveryOperation|
97 // object. This would also simplify lifetime of the object w.r.t. DialRegistry;
98 // the Registry would not need to create/destroy the Service on demand.
99 // DialServiceImpl lives on the IO thread.
100 class DialServiceImpl : public DialService {
101 public:
102 explicit DialServiceImpl(net::NetLog* net_log);
103 ~DialServiceImpl() override;
104
105 // DialService implementation
106 bool Discover() override;
107 void AddObserver(Observer* observer) override;
108 void RemoveObserver(Observer* observer) override;
109 bool HasObserver(const Observer* observer) const override;
110
111 private:
112 // Represents a socket binding to a single network interface.
113 // DialSocket lives on the IO thread.
114 class DialSocket {
115 public:
116 // TODO(imcheng): Consider writing a DialSocket::Delegate interface that
117 // declares methods for these callbacks, and taking a ptr to the delegate
118 // here.
119 DialSocket(
120 const base::Closure& discovery_request_cb,
121 const base::Callback<void(const DialDeviceData&)>& device_discovered_cb,
122 const base::Closure& on_error_cb);
123 ~DialSocket();
124
125 // Creates a socket using |net_log| and |net_log_source| and binds it to
126 // |bind_ip_address|.
127 bool CreateAndBindSocket(const net::IPAddress& bind_ip_address,
128 net::NetLog* net_log,
129 net::NetLogSource net_log_source);
130
131 // Sends a single discovery request |send_buffer| to |send_address|
132 // over the socket.
133 void SendOneRequest(const net::IPEndPoint& send_address,
134 const scoped_refptr<net::StringIOBuffer>& send_buffer);
135
136 // Returns true if the socket is closed.
137 bool IsClosed();
138
139 private:
140 // Checks the result of a socket operation. The name of the socket
141 // operation is given by |operation| and the result of the operation is
142 // given by |result|. If the result is an error, closes the socket,
143 // calls |on_error_cb_|, and returns |false|. Returns
144 // |true| otherwise. |operation| and |result| are logged.
145 bool CheckResult(const char* operation, int result);
146
147 // Closes the socket.
148 void Close();
149
150 // Callback invoked for socket writes.
151 void OnSocketWrite(int buffer_size, int result);
152
153 // Establishes the callback to read from the socket. Returns true if
154 // successful.
155 bool ReadSocket();
156
157 // Callback invoked for socket reads.
158 void OnSocketRead(int result);
159
160 // Callback invoked for socket reads.
161 void HandleResponse(int bytes_read);
162
163 // Parses a response into a DialDeviceData object. If the DIAL response is
164 // invalid or does not contain enough information, then the return
165 // value will be false and |device| is not changed.
166 static bool ParseResponse(const std::string& response,
167 const base::Time& response_time,
168 DialDeviceData* device);
169
170 // The UDP socket.
171 std::unique_ptr<net::UDPSocket> socket_;
172
173 // Buffer for socket reads.
174 scoped_refptr<net::IOBufferWithSize> recv_buffer_;
175
176 // The source of of the last socket read.
177 net::IPEndPoint recv_address_;
178
179 // The callback to be invoked when a discovery request was made.
180 base::Closure discovery_request_cb_;
181
182 // The callback to be invoked when a device has been discovered.
183 base::Callback<void(const DialDeviceData&)> device_discovered_cb_;
184
185 // The callback to be invoked when there is an error with socket operations.
186 base::Closure on_error_cb_;
187
188 // Marks whether there is an active write callback.
189 bool is_writing_;
190
191 // Marks whether there is an active read callback.
192 bool is_reading_;
193
194 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestNotifyOnError);
195 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestOnDeviceDiscovered);
196 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestOnDiscoveryRequest);
197 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestResponseParsing);
198 DISALLOW_COPY_AND_ASSIGN(DialSocket);
199 };
200
201 // Starts the control flow for one discovery cycle.
202 void StartDiscovery();
203
204 // For each network interface in |list|, finds all unqiue IPv4 network
205 // interfaces and call |DiscoverOnAddresses()| with their IP addresses.
206 void SendNetworkList(const net::NetworkInterfaceList& list);
207
208 // Calls |BindAndAddSocket()| for each address in |ip_addresses|, calls
209 // |SendOneRequest()|, and start the timer to finish discovery if needed.
210 // The (Address family, interface index) of each address in |ip_addresses|
211 // must be unique. If |ip_address| is empty, calls |FinishDiscovery()|.
212 void DiscoverOnAddresses(const net::IPAddressList& ip_addresses);
213
214 // Creates a DialSocket, binds it to |bind_ip_address| and if
215 // successful, add the DialSocket to |dial_sockets_|.
216 void BindAndAddSocket(const net::IPAddress& bind_ip_address);
217
218 // Creates a DialSocket with callbacks to this object.
219 std::unique_ptr<DialSocket> CreateDialSocket();
220
221 // Sends a single discovery request to every socket that are currently open.
222 void SendOneRequest();
223
224 // Notify observers that a discovery request was made.
225 void NotifyOnDiscoveryRequest();
226
227 // Notify observers a device has been discovered.
228 void NotifyOnDeviceDiscovered(const DialDeviceData& device_data);
229
230 // Notify observers that there has been an error with one of the DialSockets.
231 void NotifyOnError();
232
233 // Called from finish_timer_ when we are done with the current round of
234 // discovery.
235 void FinishDiscovery();
236
237 // Returns |true| if there are open sockets.
238 bool HasOpenSockets();
239
240 // DialSockets for each network interface whose ip address was
241 // successfully bound.
242 std::vector<std::unique_ptr<DialSocket>> dial_sockets_;
243
244 // The NetLog for this service.
245 net::NetLog* const net_log_;
246
247 // The NetLog source for this service.
248 net::NetLogSource net_log_source_;
249
250 // The multicast address:port for search requests.
251 net::IPEndPoint send_address_;
252
253 // Buffer for socket writes.
254 scoped_refptr<net::StringIOBuffer> send_buffer_;
255
256 // True when we are currently doing discovery.
257 bool discovery_active_;
258
259 // The number of requests that have been sent in the current discovery.
260 int num_requests_sent_;
261
262 // The maximum number of requests to send per discovery cycle.
263 int max_requests_;
264
265 // Timer for finishing discovery.
266 base::OneShotTimer finish_timer_;
267
268 // The delay for |finish_timer_|; how long to wait for discovery to finish.
269 // Setting this to zero disables the timer.
270 base::TimeDelta finish_delay_;
271
272 // Timer for sending multiple requests at fixed intervals.
273 base::RepeatingTimer request_timer_;
274
275 // The delay for |request_timer_|; how long to wait between successive
276 // requests.
277 base::TimeDelta request_interval_;
278
279 // List of observers.
280 base::ObserverList<Observer> observer_list_;
281
282 base::WeakPtrFactory<DialServiceImpl> weak_factory_;
283
284 friend class DialServiceTest;
285 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestSendMultipleRequests);
286 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestMultipleNetworkInterfaces);
287 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestNotifyOnError);
288 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestOnDeviceDiscovered);
289 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestOnDiscoveryFinished);
290 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestOnDiscoveryRequest);
291 FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestResponseParsing);
292 DISALLOW_COPY_AND_ASSIGN(DialServiceImpl);
293 };
294
295 } // namespace dial
296 } // namespace api
297 } // namespace extensions
298
299 #endif // CHROME_BROWSER_EXTENSIONS_API_DIAL_DIAL_SERVICE_H_
OLDNEW
« no previous file with comments | « chrome/browser/extensions/api/dial/dial_registry_unittest.cc ('k') | chrome/browser/extensions/api/dial/dial_service.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698