- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / extensions / api / dial / dial_service.h
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 <string>
9
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"
18
19 namespace net {
20 class IPEndPoint;
21 class IPAddress;
22 class IOBuffer;
23 class StringIOBuffer;
24 struct NetworkInterface;
25 }
26
27 namespace extensions {
28
29 class DialDeviceData;
30
31 // DialService accepts requests to discover devices, sends multiple M-SEARCH
32 // requests via UDP multicast, and notifies observers when a DIAL-compliant
33 // device responds.
34 //
35 // Each time Discover() is called, kDialNumRequests M-SEARCH requests are sent
36 // (with a delay of kDialRequestIntervalMillis in between):
37 //
38 // Time    Action
39 // ----    ------
40 // T1      Request 1 sent, OnDiscoveryReqest() called
41 // ...
42 // Tk      Request kDialNumRequests sent, OnDiscoveryReqest() called
43 // Tf      OnDiscoveryFinished() called
44 //
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).
48 //
49 // Calling Discover() again between T1 and Tf has no effect.
50 //
51 // All relevant constants are defined in dial_service.cc.
52 //
53 // TODO(mfoltz): Port this into net/.
54 // See https://code.google.com/p/chromium/issues/detail?id=164473
55 class DialService {
56  public:
57   enum DialServiceErrorCode {
58     DIAL_SERVICE_NO_INTERFACES = 0,
59     DIAL_SERVICE_SOCKET_ERROR
60   };
61
62   class Observer {
63    public:
64     // Called when a single discovery request was sent.
65     virtual void OnDiscoveryRequest(DialService* service) = 0;
66
67     // Called when a device responds to a request.
68     virtual void OnDeviceDiscovered(DialService* service,
69                                     const DialDeviceData& device) = 0;
70
71     // Called when we have all responses from the last discovery request.
72     virtual void OnDiscoveryFinished(DialService* service) = 0;
73
74     // Called when an error occurs.
75     virtual void OnError(DialService* service,
76                          const DialServiceErrorCode& code) = 0;
77
78    protected:
79     virtual ~Observer() {}
80   };
81
82   virtual ~DialService() {}
83
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;
87
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;
92 };
93
94 // Implements DialService.
95 //
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> {
102  public:
103   explicit DialServiceImpl(net::NetLog* net_log);
104   virtual ~DialServiceImpl();
105
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;
111
112  private:
113   // Starts the control flow for one discovery cycle.
114   void StartDiscovery();
115
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);
120
121   // Sends a single discovery request over the socket.
122   void SendOneRequest();
123
124   // Callback invoked for socket writes.
125   void OnSocketWrite(int result);
126
127   // Send the network list to IO thread.
128   void SendNetworkList(const net::NetworkInterfaceList& list);
129
130   // Establishes the callback to read from the socket.  Returns true if
131   // successful.
132   bool ReadSocket();
133
134   // Callback invoked for socket reads.
135   void OnSocketRead(int result);
136
137   // Handles |bytes_read| bytes read from the socket and calls ReadSocket to
138   // await the next response.
139   void HandleResponse(int bytes_read);
140
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);
147
148   // Called from finish_timer_ when we are done with the current round of
149   // discovery.
150   void FinishDiscovery();
151
152   // Closes the socket.
153   void CloseSocket();
154
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
157   // |true| otherwise.
158   bool CheckResult(const char* operation, int result);
159
160   // The UDP socket.
161   scoped_ptr<net::UDPSocket> socket_;
162
163   // The multicast address:port for search requests.
164   net::IPEndPoint send_address_;
165
166   // The NetLog for this service.
167   net::NetLog* net_log_;
168
169   // The NetLog source for this service.
170   net::NetLog::Source net_log_source_;
171
172   // Buffer for socket writes.
173   scoped_refptr<net::StringIOBuffer> send_buffer_;
174
175   // Marks whether there is an active write callback.
176   bool is_writing_;
177
178   // Buffer for socket reads.
179   scoped_refptr<net::IOBufferWithSize> recv_buffer_;
180
181   // The source of of the last socket read.
182   net::IPEndPoint recv_address_;
183
184   // Marks whether there is an active read callback.
185   bool is_reading_;
186
187   // True when we are currently doing discovery.
188   bool discovery_active_;
189
190   // The number of requests that have been sent in the current discovery.
191   int num_requests_sent_;
192
193   // The maximum number of requests to send per discovery cycle.
194   int max_requests_;
195
196   // Timer for finishing discovery.
197   base::OneShotTimer<DialServiceImpl> finish_timer_;
198
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_;
202
203   // Timer for sending multiple requests at fixed intervals.
204   base::RepeatingTimer<DialServiceImpl> request_timer_;
205
206   // The delay for |request_timer_|; how long to wait between successive
207   // requests.
208   base::TimeDelta request_interval_;
209
210   // List of observers.
211   ObserverList<Observer> observer_list_;
212
213   // Thread checker.
214   base::ThreadChecker thread_checker_;
215
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);
222 };
223
224 }  // namespace extensions
225
226 #endif  // CHROME_BROWSER_EXTENSIONS_API_DIAL_DIAL_SERVICE_H_