Home | History | Annotate | Download | only in dial
      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 #if defined(OS_CHROMEOS)
    117   // Returns the IP address of the preferred interface to bind the socket. This
    118   // ChromeOS version can prioritize wifi and ethernet interfaces.
    119   net::IPAddressNumber GetBestBindAddressChromeOS();
    120 #endif
    121 
    122   // Establishes the UDP socket that is used for requests and responses,
    123   // establishes a read callback on the socket, and sends the first discovery
    124   // request.  Returns true if successful.
    125   bool BindSocketAndSendRequest(const net::IPAddressNumber& bind_ip_address);
    126 
    127   // Sends a single discovery request over the socket.
    128   void SendOneRequest();
    129 
    130   // Callback invoked for socket writes.
    131   void OnSocketWrite(int result);
    132 
    133   // Send the network list to IO thread.
    134   void SendNetworkList(const net::NetworkInterfaceList& list);
    135 
    136   // Establishes the callback to read from the socket.  Returns true if
    137   // successful.
    138   bool ReadSocket();
    139 
    140   // Callback invoked for socket reads.
    141   void OnSocketRead(int result);
    142 
    143   // Handles |bytes_read| bytes read from the socket and calls ReadSocket to
    144   // await the next response.
    145   void HandleResponse(int bytes_read);
    146 
    147   // Parses a response into a DialDeviceData object. If the DIAL response is
    148   // invalid or does not contain enough information, then the return
    149   // value will be false and |device| is not changed.
    150   static bool ParseResponse(const std::string& response,
    151                             const base::Time& response_time,
    152                             DialDeviceData* device);
    153 
    154   // Called from finish_timer_ when we are done with the current round of
    155   // discovery.
    156   void FinishDiscovery();
    157 
    158   // Closes the socket.
    159   void CloseSocket();
    160 
    161   // Checks the result of a socket operation.  If the result is an error, closes
    162   // the socket, notifies observers via OnError(), and returns |false|.  Returns
    163   // |true| otherwise.
    164   bool CheckResult(const char* operation, int result);
    165 
    166   // The UDP socket.
    167   scoped_ptr<net::UDPSocket> socket_;
    168 
    169   // The multicast address:port for search requests.
    170   net::IPEndPoint send_address_;
    171 
    172   // The NetLog for this service.
    173   net::NetLog* net_log_;
    174 
    175   // The NetLog source for this service.
    176   net::NetLog::Source net_log_source_;
    177 
    178   // Buffer for socket writes.
    179   scoped_refptr<net::StringIOBuffer> send_buffer_;
    180 
    181   // Marks whether there is an active write callback.
    182   bool is_writing_;
    183 
    184   // Buffer for socket reads.
    185   scoped_refptr<net::IOBufferWithSize> recv_buffer_;
    186 
    187   // The source of of the last socket read.
    188   net::IPEndPoint recv_address_;
    189 
    190   // Marks whether there is an active read callback.
    191   bool is_reading_;
    192 
    193   // True when we are currently doing discovery.
    194   bool discovery_active_;
    195 
    196   // The number of requests that have been sent in the current discovery.
    197   int num_requests_sent_;
    198 
    199   // The maximum number of requests to send per discovery cycle.
    200   int max_requests_;
    201 
    202   // Timer for finishing discovery.
    203   base::OneShotTimer<DialServiceImpl> finish_timer_;
    204 
    205   // The delay for |finish_timer_|; how long to wait for discovery to finish.
    206   // Setting this to zero disables the timer.
    207   base::TimeDelta finish_delay_;
    208 
    209   // Timer for sending multiple requests at fixed intervals.
    210   base::RepeatingTimer<DialServiceImpl> request_timer_;
    211 
    212   // The delay for |request_timer_|; how long to wait between successive
    213   // requests.
    214   base::TimeDelta request_interval_;
    215 
    216   // List of observers.
    217   ObserverList<Observer> observer_list_;
    218 
    219   // Thread checker.
    220   base::ThreadChecker thread_checker_;
    221 
    222   FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestSendMultipleRequests);
    223   FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestOnDeviceDiscovered);
    224   FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestOnDiscoveryFinished);
    225   FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestOnDiscoveryRequest);
    226   FRIEND_TEST_ALL_PREFIXES(DialServiceTest, TestResponseParsing);
    227   DISALLOW_COPY_AND_ASSIGN(DialServiceImpl);
    228 };
    229 
    230 }  // namespace extensions
    231 
    232 #endif  // CHROME_BROWSER_EXTENSIONS_API_DIAL_DIAL_SERVICE_H_
    233