3 * Copyright 2004--2005, Google Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 // A Transport manages a set of named channels of the same type.
30 // Subclasses choose the appropriate class to instantiate for each channel;
31 // however, this base class keeps track of the channels by name, watches their
32 // state changes (in order to update the manager's state), and forwards
33 // requests to begin connecting or to reset to each of the channels.
35 // On Threading: Transport performs work on both the signaling and worker
36 // threads. For subclasses, the rule is that all signaling related calls will
37 // be made on the signaling thread and all channel related calls (including
38 // signaling for a channel) will be made on the worker thread. When
39 // information needs to be sent between the two threads, this class should do
40 // the work (e.g., OnRemoteCandidate).
42 // Note: Subclasses must call DestroyChannels() in their own constructors.
43 // It is not possible to do so here because the subclass constructor will
46 #ifndef TALK_P2P_BASE_TRANSPORT_H_
47 #define TALK_P2P_BASE_TRANSPORT_H_
52 #include "talk/base/criticalsection.h"
53 #include "talk/base/messagequeue.h"
54 #include "talk/base/sigslot.h"
55 #include "talk/base/sslstreamadapter.h"
56 #include "talk/p2p/base/candidate.h"
57 #include "talk/p2p/base/constants.h"
58 #include "talk/p2p/base/sessiondescription.h"
59 #include "talk/p2p/base/transportinfo.h"
74 class CandidateTranslator;
78 class TransportChannel;
79 class TransportChannelImpl;
81 typedef std::vector<buzz::XmlElement*> XmlElements;
82 typedef std::vector<Candidate> Candidates;
84 // Used to parse and serialize (write) transport candidates. For
85 // convenience of old code, Transports will implement TransportParser.
86 // Parse/Write seems better than Serialize/Deserialize or
88 class TransportParser {
90 // The incoming Translator value may be null, in which case
91 // ParseCandidates should return false if there are candidates to
92 // parse (indicating a failure to parse). If the Translator is null
93 // and there are no candidates to parse, then return true,
94 // indicating a successful parse of 0 candidates.
96 // Parse or write a transport description, including ICE credentials and
97 // any DTLS fingerprint. Since only Jingle has transport descriptions, these
98 // functions are only used when serializing to Jingle.
99 virtual bool ParseTransportDescription(const buzz::XmlElement* elem,
100 const CandidateTranslator* translator,
101 TransportDescription* tdesc,
102 ParseError* error) = 0;
103 virtual bool WriteTransportDescription(const TransportDescription& tdesc,
104 const CandidateTranslator* translator,
105 buzz::XmlElement** tdesc_elem,
106 WriteError* error) = 0;
109 // Parse a single candidate. This must be used when parsing Gingle
110 // candidates, since there is no enclosing transport description.
111 virtual bool ParseGingleCandidate(const buzz::XmlElement* elem,
112 const CandidateTranslator* translator,
113 Candidate* candidates,
114 ParseError* error) = 0;
115 virtual bool WriteGingleCandidate(const Candidate& candidate,
116 const CandidateTranslator* translator,
117 buzz::XmlElement** candidate_elem,
118 WriteError* error) = 0;
120 // Helper function to parse an element describing an address. This
121 // retrieves the IP and port from the given element and verifies
122 // that they look like plausible values.
123 bool ParseAddress(const buzz::XmlElement* elem,
124 const buzz::QName& address_name,
125 const buzz::QName& port_name,
126 talk_base::SocketAddress* address,
129 virtual ~TransportParser() {}
132 // For "writable" and "readable", we need to differentiate between
133 // none, all, and some.
134 enum TransportState {
135 TRANSPORT_STATE_NONE = 0,
136 TRANSPORT_STATE_SOME,
140 // Stats that we can return about the connections for a transport channel.
141 // TODO(hta): Rename to ConnectionStats
142 struct ConnectionInfo {
144 : best_connection(false),
148 new_connection(false),
151 sent_bytes_second(0),
153 recv_bytes_second(0),
156 bool best_connection; // Is this the best connection we have?
157 bool writable; // Has this connection received a STUN response?
158 bool readable; // Has this connection received a STUN request?
159 bool timeout; // Has this connection timed out?
160 bool new_connection; // Is this a newly created connection?
161 size_t rtt; // The STUN RTT for this connection.
162 size_t sent_total_bytes; // Total bytes sent on this connection.
163 size_t sent_bytes_second; // Bps over the last measurement interval.
164 size_t recv_total_bytes; // Total bytes received on this connection.
165 size_t recv_bytes_second; // Bps over the last measurement interval.
166 Candidate local_candidate; // The local candidate for this connection.
167 Candidate remote_candidate; // The remote candidate for this connection.
168 void* key; // A static value that identifies this conn.
171 // Information about all the connections of a channel.
172 typedef std::vector<ConnectionInfo> ConnectionInfos;
174 // Information about a specific channel
175 struct TransportChannelStats {
177 ConnectionInfos connection_infos;
180 // Information about all the channels of a transport.
181 // TODO(hta): Consider if a simple vector is as good as a map.
182 typedef std::vector<TransportChannelStats> TransportChannelStatsList;
184 // Information about the stats of a transport.
185 struct TransportStats {
186 std::string content_name;
187 TransportChannelStatsList channel_stats;
190 bool BadTransportDescription(const std::string& desc, std::string* err_desc);
192 class Transport : public talk_base::MessageHandler,
193 public sigslot::has_slots<> {
195 Transport(talk_base::Thread* signaling_thread,
196 talk_base::Thread* worker_thread,
197 const std::string& content_name,
198 const std::string& type,
199 PortAllocator* allocator);
200 virtual ~Transport();
202 // Returns the signaling thread. The app talks to Transport on this thread.
203 talk_base::Thread* signaling_thread() { return signaling_thread_; }
204 // Returns the worker thread. The actual networking is done on this thread.
205 talk_base::Thread* worker_thread() { return worker_thread_; }
207 // Returns the content_name of this transport.
208 const std::string& content_name() const { return content_name_; }
209 // Returns the type of this transport.
210 const std::string& type() const { return type_; }
212 // Returns the port allocator object for this transport.
213 PortAllocator* port_allocator() { return allocator_; }
215 // Returns the readable and states of this manager. These bits are the ORs
216 // of the corresponding bits on the managed channels. Each time one of these
217 // states changes, a signal is raised.
218 // TODO: Replace uses of readable() and writable() with
219 // any_channels_readable() and any_channels_writable().
220 bool readable() const { return any_channels_readable(); }
221 bool writable() const { return any_channels_writable(); }
222 bool was_writable() const { return was_writable_; }
223 bool any_channels_readable() const {
224 return (readable_ == TRANSPORT_STATE_SOME ||
225 readable_ == TRANSPORT_STATE_ALL);
227 bool any_channels_writable() const {
228 return (writable_ == TRANSPORT_STATE_SOME ||
229 writable_ == TRANSPORT_STATE_ALL);
231 bool all_channels_readable() const {
232 return (readable_ == TRANSPORT_STATE_ALL);
234 bool all_channels_writable() const {
235 return (writable_ == TRANSPORT_STATE_ALL);
237 sigslot::signal1<Transport*> SignalReadableState;
238 sigslot::signal1<Transport*> SignalWritableState;
240 bool completed() const;
241 sigslot::signal1<Transport*> SignalCompleted;
242 sigslot::signal1<Transport*> SignalFailed;
244 // Returns whether the client has requested the channels to connect.
245 bool connect_requested() const { return connect_requested_; }
247 void SetIceRole(IceRole role);
248 IceRole ice_role() const { return ice_role_; }
250 void SetIceTiebreaker(uint64 IceTiebreaker) { tiebreaker_ = IceTiebreaker; }
251 uint64 IceTiebreaker() { return tiebreaker_; }
253 // Must be called before applying local session description.
254 void SetIdentity(talk_base::SSLIdentity* identity);
256 // Get a copy of the local identity provided by SetIdentity.
257 bool GetIdentity(talk_base::SSLIdentity** identity);
259 // Get a copy of the remote certificate in use by the specified channel.
260 bool GetRemoteCertificate(talk_base::SSLCertificate** cert);
262 TransportProtocol protocol() const { return protocol_; }
264 // Create, destroy, and lookup the channels of this type by their components.
265 TransportChannelImpl* CreateChannel(int component);
266 // Note: GetChannel may lead to race conditions, since the mutex is not held
267 // after the pointer is returned.
268 TransportChannelImpl* GetChannel(int component);
269 // Note: HasChannel does not lead to race conditions, unlike GetChannel.
270 bool HasChannel(int component) {
271 return (NULL != GetChannel(component));
274 void DestroyChannel(int component);
276 // Set the local TransportDescription to be used by TransportChannels.
277 // This should be called before ConnectChannels().
278 bool SetLocalTransportDescription(const TransportDescription& description,
279 ContentAction action,
280 std::string* error_desc);
282 // Set the remote TransportDescription to be used by TransportChannels.
283 bool SetRemoteTransportDescription(const TransportDescription& description,
284 ContentAction action,
285 std::string* error_desc);
287 // Tells all current and future channels to start connecting. When the first
288 // channel begins connecting, the following signal is raised.
289 void ConnectChannels();
290 sigslot::signal1<Transport*> SignalConnecting;
292 // Resets all of the channels back to their initial state. They are no
293 // longer connecting.
294 void ResetChannels();
296 // Destroys every channel created so far.
297 void DestroyAllChannels();
299 bool GetStats(TransportStats* stats);
301 // Before any stanza is sent, the manager will request signaling. Once
302 // signaling is available, the client should call OnSignalingReady. Once
303 // this occurs, the transport (or its channels) can send any waiting stanzas.
304 // OnSignalingReady invokes OnTransportSignalingReady and then forwards this
305 // signal to each channel.
306 sigslot::signal1<Transport*> SignalRequestSignaling;
307 void OnSignalingReady();
309 // Handles sending of ready candidates and receiving of remote candidates.
310 sigslot::signal2<Transport*,
311 const std::vector<Candidate>&> SignalCandidatesReady;
313 sigslot::signal1<Transport*> SignalCandidatesAllocationDone;
314 void OnRemoteCandidates(const std::vector<Candidate>& candidates);
316 // If candidate is not acceptable, returns false and sets error.
317 // Call this before calling OnRemoteCandidates.
318 virtual bool VerifyCandidate(const Candidate& candidate,
321 // Signals when the best connection for a channel changes.
322 sigslot::signal3<Transport*,
324 const Candidate&> SignalRouteChange;
326 // A transport message has generated an transport-specific error. The
327 // stanza that caused the error is available in session_msg. If false is
328 // returned, the error is considered unrecoverable, and the session is
330 // TODO(juberti): Remove these obsolete functions once Session no longer
332 virtual void OnTransportError(const buzz::XmlElement* error) {}
333 sigslot::signal6<Transport*, const buzz::XmlElement*, const buzz::QName&,
334 const std::string&, const std::string&,
335 const buzz::XmlElement*>
336 SignalTransportError;
338 // Forwards the signal from TransportChannel to BaseSession.
339 sigslot::signal0<> SignalRoleConflict;
341 virtual bool GetSslRole(talk_base::SSLRole* ssl_role) const;
344 // These are called by Create/DestroyChannel above in order to create or
345 // destroy the appropriate type of channel.
346 virtual TransportChannelImpl* CreateTransportChannel(int component) = 0;
347 virtual void DestroyTransportChannel(TransportChannelImpl* channel) = 0;
349 // Informs the subclass that we received the signaling ready message.
350 virtual void OnTransportSignalingReady() {}
352 // The current local transport description, for use by derived classes
353 // when performing transport description negotiation.
354 const TransportDescription* local_description() const {
355 return local_description_.get();
358 // The current remote transport description, for use by derived classes
359 // when performing transport description negotiation.
360 const TransportDescription* remote_description() const {
361 return remote_description_.get();
364 virtual void SetIdentity_w(talk_base::SSLIdentity* identity) {}
366 virtual bool GetIdentity_w(talk_base::SSLIdentity** identity) {
370 // Pushes down the transport parameters from the local description, such
371 // as the ICE ufrag and pwd.
372 // Derived classes can override, but must call the base as well.
373 virtual bool ApplyLocalTransportDescription_w(TransportChannelImpl* channel,
374 std::string* error_desc);
376 // Pushes down remote ice credentials from the remote description to the
377 // transport channel.
378 virtual bool ApplyRemoteTransportDescription_w(TransportChannelImpl* ch,
379 std::string* error_desc);
381 // Negotiates the transport parameters based on the current local and remote
382 // transport description, such at the version of ICE to use, and whether DTLS
383 // should be activated.
384 // Derived classes can negotiate their specific parameters here, but must call
386 virtual bool NegotiateTransportDescription_w(ContentAction local_role,
387 std::string* error_desc);
389 // Pushes down the transport parameters obtained via negotiation.
390 // Derived classes can set their specific parameters here, but must call the
392 virtual bool ApplyNegotiatedTransportDescription_w(
393 TransportChannelImpl* channel, std::string* error_desc);
395 virtual bool GetSslRole_w(talk_base::SSLRole* ssl_role) const {
400 struct ChannelMapEntry {
401 ChannelMapEntry() : impl_(NULL), candidates_allocated_(false), ref_(0) {}
402 explicit ChannelMapEntry(TransportChannelImpl *impl)
404 candidates_allocated_(false),
408 void AddRef() { ++ref_; }
413 int ref() const { return ref_; }
415 TransportChannelImpl* get() const { return impl_; }
416 TransportChannelImpl* operator->() const { return impl_; }
417 void set_candidates_allocated(bool status) {
418 candidates_allocated_ = status;
420 bool candidates_allocated() const { return candidates_allocated_; }
423 TransportChannelImpl *impl_;
424 bool candidates_allocated_;
428 // Candidate component => ChannelMapEntry
429 typedef std::map<int, ChannelMapEntry> ChannelMap;
431 // Called when the state of a channel changes.
432 void OnChannelReadableState(TransportChannel* channel);
433 void OnChannelWritableState(TransportChannel* channel);
435 // Called when a channel requests signaling.
436 void OnChannelRequestSignaling(TransportChannelImpl* channel);
438 // Called when a candidate is ready from remote peer.
439 void OnRemoteCandidate(const Candidate& candidate);
440 // Called when a candidate is ready from channel.
441 void OnChannelCandidateReady(TransportChannelImpl* channel,
442 const Candidate& candidate);
443 void OnChannelRouteChange(TransportChannel* channel,
444 const Candidate& remote_candidate);
445 void OnChannelCandidatesAllocationDone(TransportChannelImpl* channel);
446 // Called when there is ICE role change.
447 void OnRoleConflict(TransportChannelImpl* channel);
448 // Called when the channel removes a connection.
449 void OnChannelConnectionRemoved(TransportChannelImpl* channel);
451 // Dispatches messages to the appropriate handler (below).
452 void OnMessage(talk_base::Message* msg);
454 // These are versions of the above methods that are called only on a
455 // particular thread (s = signaling, w = worker). The above methods post or
456 // send a message to invoke this version.
457 TransportChannelImpl* CreateChannel_w(int component);
458 void DestroyChannel_w(int component);
459 void ConnectChannels_w();
460 void ResetChannels_w();
461 void DestroyAllChannels_w();
462 void OnRemoteCandidate_w(const Candidate& candidate);
463 void OnChannelReadableState_s();
464 void OnChannelWritableState_s();
465 void OnChannelRequestSignaling_s(int component);
466 void OnConnecting_s();
467 void OnChannelRouteChange_s(const TransportChannel* channel,
468 const Candidate& remote_candidate);
469 void OnChannelCandidatesAllocationDone_s();
471 // Helper function that invokes the given function on every channel.
472 typedef void (TransportChannelImpl::* TransportChannelFunc)();
473 void CallChannels_w(TransportChannelFunc func);
475 // Computes the OR of the channel's read or write state (argument picks).
476 TransportState GetTransportState_s(bool read);
478 void OnChannelCandidateReady_s();
480 void SetIceRole_w(IceRole role);
481 void SetRemoteIceMode_w(IceMode mode);
482 bool SetLocalTransportDescription_w(const TransportDescription& desc,
483 ContentAction action,
484 std::string* error_desc);
485 bool SetRemoteTransportDescription_w(const TransportDescription& desc,
486 ContentAction action,
487 std::string* error_desc);
488 bool GetStats_w(TransportStats* infos);
489 bool GetRemoteCertificate_w(talk_base::SSLCertificate** cert);
492 talk_base::Thread* signaling_thread_;
493 talk_base::Thread* worker_thread_;
494 std::string content_name_;
496 PortAllocator* allocator_;
498 TransportState readable_;
499 TransportState writable_;
501 bool connect_requested_;
504 TransportProtocol protocol_;
505 IceMode remote_ice_mode_;
506 talk_base::scoped_ptr<TransportDescription> local_description_;
507 talk_base::scoped_ptr<TransportDescription> remote_description_;
509 ChannelMap channels_;
510 // Buffers the ready_candidates so that SignalCanidatesReady can
511 // provide them in multiples.
512 std::vector<Candidate> ready_candidates_;
513 // Protects changes to channels and messages
514 talk_base::CriticalSection crit_;
516 DISALLOW_EVIL_CONSTRUCTORS(Transport);
519 // Extract a TransportProtocol from a TransportDescription.
520 TransportProtocol TransportProtocolFromDescription(
521 const TransportDescription* desc);
523 } // namespace cricket
525 #endif // TALK_P2P_BASE_TRANSPORT_H_