1 /*
2  *  Copyright 2015 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #ifndef WEBRTC_P2P_BASE_TRANSPORTCONTROLLER_H_
12 #define WEBRTC_P2P_BASE_TRANSPORTCONTROLLER_H_
13 
14 #include <map>
15 #include <memory>
16 #include <string>
17 #include <vector>
18 
19 #include "webrtc/base/asyncinvoker.h"
20 #include "webrtc/base/constructormagic.h"
21 #include "webrtc/base/refcountedobject.h"
22 #include "webrtc/base/sigslot.h"
23 #include "webrtc/base/sslstreamadapter.h"
24 #include "webrtc/p2p/base/candidate.h"
25 #include "webrtc/p2p/base/dtlstransportchannel.h"
26 #include "webrtc/p2p/base/jseptransport.h"
27 #include "webrtc/p2p/base/p2ptransportchannel.h"
28 
29 namespace rtc {
30 class Thread;
31 class PacketTransportInterface;
32 }
33 namespace webrtc {
34 class MetricsObserverInterface;
35 }
36 
37 namespace cricket {
38 
39 class TransportController : public sigslot::has_slots<>,
40                             public rtc::MessageHandler {
41  public:
42   // If |redetermine_role_on_ice_restart| is true, ICE role is redetermined
43   // upon setting a local transport description that indicates an ICE restart.
44   // For the constructor that doesn't take this parameter, it defaults to true.
45   TransportController(rtc::Thread* signaling_thread,
46                       rtc::Thread* network_thread,
47                       PortAllocator* port_allocator,
48                       bool redetermine_role_on_ice_restart);
49 
50   TransportController(rtc::Thread* signaling_thread,
51                       rtc::Thread* network_thread,
52                       PortAllocator* port_allocator);
53 
54   virtual ~TransportController();
55 
signaling_thread()56   rtc::Thread* signaling_thread() const { return signaling_thread_; }
network_thread()57   rtc::Thread* network_thread() const { return network_thread_; }
58 
port_allocator()59   PortAllocator* port_allocator() const { return port_allocator_; }
60 
61   // Can only be set before transports are created.
62   // TODO(deadbeef): Make this an argument to the constructor once BaseSession
63   // and WebRtcSession are combined
64   bool SetSslMaxProtocolVersion(rtc::SSLProtocolVersion version);
65 
66   void SetIceConfig(const IceConfig& config);
67   void SetIceRole(IceRole ice_role);
68 
69   // Set the "needs-ice-restart" flag as described in JSEP. After the flag is
70   // set, offers should generate new ufrags/passwords until an ICE restart
71   // occurs.
72   void SetNeedsIceRestartFlag();
73   // Returns true if the ICE restart flag above was set, and no ICE restart has
74   // occurred yet for this transport (by applying a local description with
75   // changed ufrag/password). If the transport has been deleted as a result of
76   // bundling, returns false.
77   bool NeedsIceRestart(const std::string& transport_name) const;
78 
79   bool GetSslRole(const std::string& transport_name, rtc::SSLRole* role) const;
80 
81   // Specifies the identity to use in this session.
82   // Can only be called once.
83   bool SetLocalCertificate(
84       const rtc::scoped_refptr<rtc::RTCCertificate>& certificate);
85   bool GetLocalCertificate(
86       const std::string& transport_name,
87       rtc::scoped_refptr<rtc::RTCCertificate>* certificate) const;
88   // Caller owns returned certificate. This method mainly exists for stats
89   // reporting.
90   std::unique_ptr<rtc::SSLCertificate> GetRemoteSSLCertificate(
91       const std::string& transport_name) const;
92   bool SetLocalTransportDescription(const std::string& transport_name,
93                                     const TransportDescription& tdesc,
94                                     ContentAction action,
95                                     std::string* err);
96   bool SetRemoteTransportDescription(const std::string& transport_name,
97                                      const TransportDescription& tdesc,
98                                      ContentAction action,
99                                      std::string* err);
100   // Start gathering candidates for any new transports, or transports doing an
101   // ICE restart.
102   void MaybeStartGathering();
103   bool AddRemoteCandidates(const std::string& transport_name,
104                            const Candidates& candidates,
105                            std::string* err);
106   bool RemoveRemoteCandidates(const Candidates& candidates, std::string* err);
107   bool ReadyForRemoteCandidates(const std::string& transport_name) const;
108   // TODO(deadbeef): GetStats isn't const because all the way down to
109   // OpenSSLStreamAdapter,
110   // GetSslCipherSuite and GetDtlsSrtpCryptoSuite are not const. Fix this.
111   bool GetStats(const std::string& transport_name, TransportStats* stats);
112   void SetMetricsObserver(webrtc::MetricsObserverInterface* metrics_observer);
113 
114   // Creates a channel if it doesn't exist. Otherwise, increments a reference
115   // count and returns an existing channel.
116   TransportChannel* CreateTransportChannel(const std::string& transport_name,
117                                            int component);
118   virtual TransportChannel* CreateTransportChannel_n(
119       const std::string& transport_name,
120       int component);
121 
122   // Decrements a channel's reference count, and destroys the channel if
123   // nothing is referencing it.
124   virtual void DestroyTransportChannel_n(const std::string& transport_name,
125                                          int component);
126 
use_quic()127   void use_quic() { quic_ = true; }
quic()128   bool quic() const { return quic_; }
129 
130   // TODO(deadbeef): Remove all for_testing methods!
certificate_for_testing()131   const rtc::scoped_refptr<rtc::RTCCertificate>& certificate_for_testing()
132       const {
133     return certificate_;
134   }
135   std::vector<std::string> transport_names_for_testing();
136   std::vector<TransportChannelImpl*> channels_for_testing();
137   TransportChannelImpl* get_channel_for_testing(
138       const std::string& transport_name,
139       int component);
140 
141   // All of these signals are fired on the signalling thread.
142 
143   // If any transport failed => failed,
144   // Else if all completed => completed,
145   // Else if all connected => connected,
146   // Else => connecting
147   sigslot::signal1<IceConnectionState> SignalConnectionState;
148 
149   // Receiving if any transport is receiving
150   sigslot::signal1<bool> SignalReceiving;
151 
152   // If all transports done gathering => complete,
153   // Else if any are gathering => gathering,
154   // Else => new
155   sigslot::signal1<IceGatheringState> SignalGatheringState;
156 
157   // (transport_name, candidates)
158   sigslot::signal2<const std::string&, const Candidates&>
159       SignalCandidatesGathered;
160 
161   sigslot::signal1<const Candidates&> SignalCandidatesRemoved;
162 
163   sigslot::signal1<rtc::SSLHandshakeError> SignalDtlsHandshakeError;
164 
165  protected:
166   // TODO(deadbeef): Get rid of these virtual methods. Used by
167   // FakeTransportController currently, but FakeTransportController shouldn't
168   // even be functioning by subclassing TransportController.
169   virtual IceTransportInternal* CreateIceTransportChannel_n(
170       const std::string& transport_name,
171       int component);
172   virtual TransportChannelImpl* CreateDtlsTransportChannel_n(
173       const std::string& transport_name,
174       int component,
175       IceTransportInternal* ice);
176 
177  private:
178   void OnMessage(rtc::Message* pmsg) override;
179 
180   class ChannelPair;
181   typedef rtc::RefCountedObject<ChannelPair> RefCountedChannel;
182 
183   // Helper functions to get a channel or transport, or iterator to it (in case
184   // it needs to be erased).
185   std::vector<RefCountedChannel*>::iterator GetChannelIterator_n(
186       const std::string& transport_name,
187       int component);
188   std::vector<RefCountedChannel*>::const_iterator GetChannelIterator_n(
189       const std::string& transport_name,
190       int component) const;
191   const JsepTransport* GetJsepTransport(
192       const std::string& transport_name) const;
193   JsepTransport* GetJsepTransport(const std::string& transport_name);
194   const RefCountedChannel* GetChannel_n(const std::string& transport_name,
195                                         int component) const;
196   RefCountedChannel* GetChannel_n(const std::string& transport_name,
197                                   int component);
198 
199   JsepTransport* GetOrCreateJsepTransport(const std::string& transport_name);
200   void DestroyAllChannels_n();
201 
202   bool SetSslMaxProtocolVersion_n(rtc::SSLProtocolVersion version);
203   void SetIceConfig_n(const IceConfig& config);
204   void SetIceRole_n(IceRole ice_role);
205   bool GetSslRole_n(const std::string& transport_name,
206                     rtc::SSLRole* role) const;
207   bool SetLocalCertificate_n(
208       const rtc::scoped_refptr<rtc::RTCCertificate>& certificate);
209   bool GetLocalCertificate_n(
210       const std::string& transport_name,
211       rtc::scoped_refptr<rtc::RTCCertificate>* certificate) const;
212   std::unique_ptr<rtc::SSLCertificate> GetRemoteSSLCertificate_n(
213       const std::string& transport_name) const;
214   bool SetLocalTransportDescription_n(const std::string& transport_name,
215                                       const TransportDescription& tdesc,
216                                       ContentAction action,
217                                       std::string* err);
218   bool SetRemoteTransportDescription_n(const std::string& transport_name,
219                                        const TransportDescription& tdesc,
220                                        ContentAction action,
221                                        std::string* err);
222   void MaybeStartGathering_n();
223   bool AddRemoteCandidates_n(const std::string& transport_name,
224                              const Candidates& candidates,
225                              std::string* err);
226   bool RemoveRemoteCandidates_n(const Candidates& candidates, std::string* err);
227   bool ReadyForRemoteCandidates_n(const std::string& transport_name) const;
228   bool GetStats_n(const std::string& transport_name, TransportStats* stats);
229   void SetMetricsObserver_n(webrtc::MetricsObserverInterface* metrics_observer);
230 
231   // Handlers for signals from Transport.
232   void OnChannelWritableState_n(rtc::PacketTransportInterface* transport);
233   void OnChannelReceivingState_n(rtc::PacketTransportInterface* transport);
234   void OnChannelGatheringState_n(TransportChannelImpl* channel);
235   void OnChannelCandidateGathered_n(TransportChannelImpl* channel,
236                                     const Candidate& candidate);
237   void OnChannelCandidatesRemoved(const Candidates& candidates);
238   void OnChannelCandidatesRemoved_n(TransportChannelImpl* channel,
239                                     const Candidates& candidates);
240   void OnChannelRoleConflict_n(TransportChannelImpl* channel);
241   void OnChannelStateChanged_n(TransportChannelImpl* channel);
242 
243   void UpdateAggregateStates_n();
244 
245   void OnDtlsHandshakeError(rtc::SSLHandshakeError error);
246 
247   rtc::Thread* const signaling_thread_ = nullptr;
248   rtc::Thread* const network_thread_ = nullptr;
249   PortAllocator* const port_allocator_ = nullptr;
250 
251   std::map<std::string, std::unique_ptr<JsepTransport>> transports_;
252   std::vector<RefCountedChannel*> channels_;
253 
254   // Aggregate state for TransportChannelImpls.
255   IceConnectionState connection_state_ = kIceConnectionConnecting;
256   bool receiving_ = false;
257   IceGatheringState gathering_state_ = kIceGatheringNew;
258 
259   IceConfig ice_config_;
260   IceRole ice_role_ = ICEROLE_CONTROLLING;
261   bool redetermine_role_on_ice_restart_;
262   uint64_t ice_tiebreaker_ = rtc::CreateRandomId64();
263   rtc::SSLProtocolVersion ssl_max_version_ = rtc::SSL_PROTOCOL_DTLS_12;
264   rtc::scoped_refptr<rtc::RTCCertificate> certificate_;
265   rtc::AsyncInvoker invoker_;
266   // True if QUIC is used instead of DTLS.
267   bool quic_ = false;
268 
269   webrtc::MetricsObserverInterface* metrics_observer_ = nullptr;
270 
271   RTC_DISALLOW_COPY_AND_ASSIGN(TransportController);
272 };
273 
274 }  // namespace cricket
275 
276 #endif  // WEBRTC_P2P_BASE_TRANSPORTCONTROLLER_H_
277