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 REMOTING_HOST_CLIENT_SESSION_H_
6 #define REMOTING_HOST_CLIENT_SESSION_H_
7 
8 #include <cstdint>
9 #include <memory>
10 #include <string>
11 
12 #include "base/macros.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/sequence_checker.h"
16 #include "base/sequenced_task_runner_helpers.h"
17 #include "base/time/time.h"
18 #include "base/timer/timer.h"
19 #include "remoting/host/client_session_control.h"
20 #include "remoting/host/client_session_details.h"
21 #include "remoting/host/desktop_and_cursor_conditional_composer.h"
22 #include "remoting/host/desktop_display_info.h"
23 #include "remoting/host/desktop_environment_options.h"
24 #include "remoting/host/host_experiment_session_plugin.h"
25 #include "remoting/host/host_extension_session_manager.h"
26 #include "remoting/host/pointer_lock_detector.h"
27 #include "remoting/host/remote_input_filter.h"
28 #include "remoting/proto/action.pb.h"
29 #include "remoting/protocol/clipboard_echo_filter.h"
30 #include "remoting/protocol/clipboard_filter.h"
31 #include "remoting/protocol/clipboard_stub.h"
32 #include "remoting/protocol/connection_to_client.h"
33 #include "remoting/protocol/data_channel_manager.h"
34 #include "remoting/protocol/display_size.h"
35 #include "remoting/protocol/host_stub.h"
36 #include "remoting/protocol/input_event_tracker.h"
37 #include "remoting/protocol/input_filter.h"
38 #include "remoting/protocol/input_stub.h"
39 #include "remoting/protocol/mouse_input_filter.h"
40 #include "remoting/protocol/pairing_registry.h"
41 #include "remoting/protocol/video_stream.h"
42 #include "third_party/webrtc/modules/desktop_capture/desktop_capture_types.h"
43 #include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h"
44 #include "third_party/webrtc/modules/desktop_capture/mouse_cursor.h"
45 #include "third_party/webrtc/modules/desktop_capture/mouse_cursor_monitor.h"
46 #include "ui/events/event.h"
47 
48 namespace remoting {
49 
50 class AudioStream;
51 class DesktopEnvironment;
52 class DesktopEnvironmentFactory;
53 class InputInjector;
54 class KeyboardLayoutMonitor;
55 class MouseShapePump;
56 class ScreenControls;
57 
58 namespace protocol {
59 class VideoLayout;
60 }  // namespace protocol
61 
62 // A ClientSession keeps a reference to a connection to a client, and maintains
63 // per-client state.
64 class ClientSession : public protocol::HostStub,
65                       public protocol::ConnectionToClient::EventHandler,
66                       public protocol::VideoStream::Observer,
67                       public ClientSessionControl,
68                       public ClientSessionDetails,
69                       public PointerLockDetector::EventHandler,
70                       public webrtc::MouseCursorMonitor::Callback {
71  public:
72   // Callback interface for passing events to the ChromotingHost.
73   class EventHandler {
74    public:
75     // Called after authentication has started.
76     virtual void OnSessionAuthenticating(ClientSession* client) = 0;
77 
78     // Called after authentication has finished successfully.
79     virtual void OnSessionAuthenticated(ClientSession* client) = 0;
80 
81     // Called after we've finished connecting all channels.
82     virtual void OnSessionChannelsConnected(ClientSession* client) = 0;
83 
84     // Called after authentication has failed. Must not tear down this
85     // object. OnSessionClosed() is notified after this handler
86     // returns.
87     virtual void OnSessionAuthenticationFailed(ClientSession* client) = 0;
88 
89     // Called after connection has failed or after the client closed it.
90     virtual void OnSessionClosed(ClientSession* client) = 0;
91 
92     // Called on notification of a route change event, when a channel is
93     // connected.
94     virtual void OnSessionRouteChange(
95         ClientSession* client,
96         const std::string& channel_name,
97         const protocol::TransportRoute& route) = 0;
98 
99    protected:
~EventHandler()100     virtual ~EventHandler() {}
101   };
102 
103   // |event_handler| and |desktop_environment_factory| must outlive |this|.
104   // All |HostExtension|s in |extensions| must outlive |this|.
105   ClientSession(
106       EventHandler* event_handler,
107       std::unique_ptr<protocol::ConnectionToClient> connection,
108       DesktopEnvironmentFactory* desktop_environment_factory,
109       const DesktopEnvironmentOptions& desktop_environment_options,
110       const base::TimeDelta& max_duration,
111       scoped_refptr<protocol::PairingRegistry> pairing_registry,
112       const std::vector<HostExtension*>& extensions);
113   ~ClientSession() override;
114 
115   // Returns the set of capabilities negotiated between client and host.
capabilities()116   const std::string& capabilities() const { return capabilities_; }
117 
118   // protocol::HostStub interface.
119   void NotifyClientResolution(
120       const protocol::ClientResolution& resolution) override;
121   void ControlVideo(const protocol::VideoControl& video_control) override;
122   void ControlAudio(const protocol::AudioControl& audio_control) override;
123   void SetCapabilities(const protocol::Capabilities& capabilities) override;
124   void RequestPairing(
125       const remoting::protocol::PairingRequest& pairing_request) override;
126   void DeliverClientMessage(const protocol::ExtensionMessage& message) override;
127   void SelectDesktopDisplay(
128       const protocol::SelectDesktopDisplayRequest& select_display) override;
129   void ControlPeerConnection(
130       const protocol::PeerConnectionParameters& parameters) override;
131 
132   // protocol::ConnectionToClient::EventHandler interface.
133   void OnConnectionAuthenticating() override;
134   void OnConnectionAuthenticated() override;
135   void CreateMediaStreams() override;
136   void OnConnectionChannelsConnected() override;
137   void OnConnectionClosed(protocol::ErrorCode error) override;
138   void OnTransportProtocolChange(const std::string& protocol) override;
139   void OnRouteChange(const std::string& channel_name,
140                      const protocol::TransportRoute& route) override;
141   void OnIncomingDataChannel(
142       const std::string& channel_name,
143       std::unique_ptr<protocol::MessagePipe> pipe) override;
144 
145   // ClientSessionControl interface.
146   const std::string& client_jid() const override;
147   void DisconnectSession(protocol::ErrorCode error) override;
148   void OnLocalKeyPressed(uint32_t usb_keycode) override;
149   void OnLocalPointerMoved(const webrtc::DesktopVector& position,
150                            ui::EventType type) override;
151   void SetDisableInputs(bool disable_inputs) override;
152   void OnDesktopDisplayChanged(
153       std::unique_ptr<protocol::VideoLayout> layout) override;
154 
155   // ClientSessionDetails interface.
156   uint32_t desktop_session_id() const override;
157   ClientSessionControl* session_control() override;
158 
159   // PointerLockDetector::EventHandler interface
160   void OnPointerLockChanged(bool active) override;
161 
162   // webrtc::MouseCursorMonitor::Callback implementation.
163   void OnMouseCursor(webrtc::MouseCursor* mouse_cursor) override;
164   void OnMouseCursorPosition(const webrtc::DesktopVector& position) override;
165 
connection()166   protocol::ConnectionToClient* connection() const { return connection_.get(); }
167 
is_authenticated()168   bool is_authenticated() { return is_authenticated_; }
169 
client_capabilities()170   const std::string* client_capabilities() const {
171     return client_capabilities_.get();
172   }
173 
174   // Registers a DataChannelManager callback for testing.
175   void RegisterCreateHandlerCallbackForTesting(
176       const std::string& prefix,
177       protocol::DataChannelManager::CreateHandlerCallback constructor);
178 
179   void SetEventTimestampsSourceForTests(
180       scoped_refptr<protocol::InputEventTimestampsSource>
181           event_timestamp_source);
182 
183   // Public for tests.
184   void UpdateMouseClampingFilterOffset();
185 
186  private:
187   // Creates a proxy for sending clipboard events to the client.
188   std::unique_ptr<protocol::ClipboardStub> CreateClipboardProxy();
189 
190   void SetMouseClampingFilter(const DisplaySize& size);
191 
192   // protocol::VideoStream::Observer implementation.
193   void OnVideoSizeChanged(protocol::VideoStream* stream,
194                           const webrtc::DesktopSize& size,
195                           const webrtc::DesktopVector& dpi) override;
196 
197   void CreateActionMessageHandler(
198       std::vector<protocol::ActionRequest::Action> capabilities,
199       const std::string& channel_name,
200       std::unique_ptr<protocol::MessagePipe> pipe);
201 
202   void CreateFileTransferMessageHandler(
203       const std::string& channel_name,
204       std::unique_ptr<protocol::MessagePipe> pipe);
205 
206   void CreateRtcLogTransferMessageHandler(
207       const std::string& channel_name,
208       std::unique_ptr<protocol::MessagePipe> pipe);
209 
210   EventHandler* event_handler_;
211 
212   // Used to create a DesktopEnvironment instance for this session.
213   DesktopEnvironmentFactory* desktop_environment_factory_;
214 
215   // The DesktopEnvironmentOptions used to initialize DesktopEnvironment.
216   DesktopEnvironmentOptions desktop_environment_options_;
217 
218   // The DesktopEnvironment instance for this session.
219   std::unique_ptr<DesktopEnvironment> desktop_environment_;
220 
221   // Filter used as the final element in the input pipeline.
222   protocol::InputFilter host_input_filter_;
223 
224   // Tracker used to release pressed keys and buttons when disconnecting.
225   protocol::InputEventTracker input_tracker_;
226 
227   // Filter used to disable remote inputs during local input activity.
228   RemoteInputFilter remote_input_filter_;
229 
230   // Filter used to clamp mouse events to the current display dimensions.
231   protocol::MouseInputFilter mouse_clamping_filter_;
232 
233   // Filter used to detect transitions into and out of client-side pointer lock.
234   PointerLockDetector pointer_lock_detector_;
235 
236   // Filter to used to stop clipboard items sent from the client being echoed
237   // back to it.  It is the final element in the clipboard (client -> host)
238   // pipeline.
239   protocol::ClipboardEchoFilter clipboard_echo_filter_;
240 
241   // Filters used to manage enabling & disabling of input & clipboard.
242   protocol::InputFilter disable_input_filter_;
243   protocol::ClipboardFilter disable_clipboard_filter_;
244 
245   // Factory for weak pointers to the client clipboard stub.
246   // This must appear after |clipboard_echo_filter_|, so that it won't outlive
247   // it.
248   base::WeakPtrFactory<protocol::ClipboardStub> client_clipboard_factory_;
249 
250   // The maximum duration of this session.
251   // There is no maximum if this value is <= 0.
252   base::TimeDelta max_duration_;
253 
254   // A timer that triggers a disconnect when the maximum session duration
255   // is reached.
256   base::OneShotTimer max_duration_timer_;
257 
258   // Objects responsible for sending video, audio.
259   std::unique_ptr<protocol::VideoStream> video_stream_;
260   std::unique_ptr<protocol::AudioStream> audio_stream_;
261 
262   // The set of all capabilities supported by the client.
263   std::unique_ptr<std::string> client_capabilities_;
264 
265   // The set of all capabilities supported by the host.
266   std::string host_capabilities_;
267 
268   // The set of all capabilities negotiated between client and host.
269   std::string capabilities_;
270 
271   // Used to inject mouse and keyboard input and handle clipboard events.
272   std::unique_ptr<InputInjector> input_injector_;
273 
274   // Used to apply client-requested changes in screen resolution.
275   std::unique_ptr<ScreenControls> screen_controls_;
276 
277   // Contains the most recently gathered info about the desktop displays;
278   DesktopDisplayInfo desktop_display_info_;
279 
280   // Default DPI values to use if a display reports 0 for DPI.
281   int default_x_dpi_;
282   int default_y_dpi_;
283 
284   // The id of the desktop display to show to the user.
285   // Default is webrtc::kInvalidScreenScreenId because we need to perform
286   // an initial capture to determine if the current setup support capturing
287   // the entire desktop or if it is restricted to a single display.
288   webrtc::ScreenId show_display_id_ = webrtc::kInvalidScreenId;
289 
290   // The initial video size captured by WebRTC.
291   // This will be the full desktop unless webrtc cannot capture the entire
292   // desktop (e.g., because the DPIs don't match). In that case, it will
293   // be equal to the dimensions of the default display.
294   DisplaySize default_webrtc_desktop_size_;
295 
296   // The current size of the area being captured by webrtc. This will be
297   // equal to the size of the entire desktop, or to a single display.
298   DisplaySize webrtc_capture_size_;
299 
300   // Set to true if the current display configuration supports capturing the
301   // entire desktop.
302   bool can_capture_full_desktop_ = true;
303 
304   // The pairing registry for PIN-less authentication.
305   scoped_refptr<protocol::PairingRegistry> pairing_registry_;
306 
307   // Used to dispatch new data channels to factory methods.
308   protocol::DataChannelManager data_channel_manager_;
309 
310   // Set to true if the client was authenticated successfully.
311   bool is_authenticated_ = false;
312 
313   // Set to true after all data channels have been connected.
314   bool channels_connected_ = false;
315 
316   // Used to store video channel pause & lossless parameters.
317   bool pause_video_ = false;
318   bool lossless_video_encode_ = false;
319   bool lossless_video_color_ = false;
320 
321   // VideoLayout is sent only after the control channel is connected. Until
322   // then it's stored in |pending_video_layout_message_|.
323   std::unique_ptr<protocol::VideoLayout> pending_video_layout_message_;
324 
325   scoped_refptr<protocol::InputEventTimestampsSource>
326       event_timestamp_source_for_tests_;
327 
328   HostExperimentSessionPlugin host_experiment_session_plugin_;
329 
330   // The connection to the client.
331   std::unique_ptr<protocol::ConnectionToClient> connection_;
332 
333   std::string client_jid_;
334 
335   // Used to manage extension functionality.
336   std::unique_ptr<HostExtensionSessionManager> extension_manager_;
337 
338   // Objects to monitor and send updates for mouse shape and keyboard layout.
339   std::unique_ptr<MouseShapePump> mouse_shape_pump_;
340   std::unique_ptr<KeyboardLayoutMonitor> keyboard_layout_monitor_;
341 
342   base::WeakPtr<DesktopAndCursorConditionalComposer>
343       desktop_and_cursor_composer_;
344 
345   SEQUENCE_CHECKER(sequence_checker_);
346 
347   // Used to disable callbacks to |this| once DisconnectSession() has been
348   // called.
349   base::WeakPtrFactory<ClientSessionControl> weak_factory_{this};
350 
351   DISALLOW_COPY_AND_ASSIGN(ClientSession);
352 };
353 
354 }  // namespace remoting
355 
356 #endif  // REMOTING_HOST_CLIENT_SESSION_H_
357