1 /* 2 * libjingle 3 * Copyright 2004--2005, Google Inc. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions are met: 7 * 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. 15 * 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. 26 */ 27 28 // A Transport manages a set of named channels of the same type. 29 // 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. 34 // 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). 41 // 42 // Note: Subclasses must call DestroyChannels() in their own constructors. 43 // It is not possible to do so here because the subclass constructor will 44 // already have run. 45 46 #ifndef TALK_P2P_BASE_TRANSPORT_H_ 47 #define TALK_P2P_BASE_TRANSPORT_H_ 48 49 #include <string> 50 #include <map> 51 #include <vector> 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" 60 61 namespace talk_base { 62 class Thread; 63 } 64 65 namespace buzz { 66 class QName; 67 class XmlElement; 68 } 69 70 namespace cricket { 71 72 struct ParseError; 73 struct WriteError; 74 class CandidateTranslator; 75 class PortAllocator; 76 class SessionManager; 77 class Session; 78 class TransportChannel; 79 class TransportChannelImpl; 80 81 typedef std::vector<buzz::XmlElement*> XmlElements; 82 typedef std::vector<Candidate> Candidates; 83 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 87 // Create/Translate. 88 class TransportParser { 89 public: 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. 95 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; 107 108 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; 119 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, 127 ParseError* error); 128 ~TransportParser()129 virtual ~TransportParser() {} 130 }; 131 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, 137 TRANSPORT_STATE_ALL 138 }; 139 140 // Stats that we can return about the connections for a transport channel. 141 // TODO(hta): Rename to ConnectionStats 142 struct ConnectionInfo { ConnectionInfoConnectionInfo143 ConnectionInfo() 144 : best_connection(false), 145 writable(false), 146 readable(false), 147 timeout(false), 148 new_connection(false), 149 rtt(0), 150 sent_total_bytes(0), 151 sent_bytes_second(0), 152 recv_total_bytes(0), 153 recv_bytes_second(0), 154 key(NULL) {} 155 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. 169 }; 170 171 // Information about all the connections of a channel. 172 typedef std::vector<ConnectionInfo> ConnectionInfos; 173 174 // Information about a specific channel 175 struct TransportChannelStats { 176 int component; 177 ConnectionInfos connection_infos; 178 }; 179 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; 183 184 // Information about the stats of a transport. 185 struct TransportStats { 186 std::string content_name; 187 TransportChannelStatsList channel_stats; 188 }; 189 190 class Transport : public talk_base::MessageHandler, 191 public sigslot::has_slots<> { 192 public: 193 Transport(talk_base::Thread* signaling_thread, 194 talk_base::Thread* worker_thread, 195 const std::string& content_name, 196 const std::string& type, 197 PortAllocator* allocator); 198 virtual ~Transport(); 199 200 // Returns the signaling thread. The app talks to Transport on this thread. signaling_thread()201 talk_base::Thread* signaling_thread() { return signaling_thread_; } 202 // Returns the worker thread. The actual networking is done on this thread. worker_thread()203 talk_base::Thread* worker_thread() { return worker_thread_; } 204 205 // Returns the content_name of this transport. content_name()206 const std::string& content_name() const { return content_name_; } 207 // Returns the type of this transport. type()208 const std::string& type() const { return type_; } 209 210 // Returns the port allocator object for this transport. port_allocator()211 PortAllocator* port_allocator() { return allocator_; } 212 213 // Returns the readable and states of this manager. These bits are the ORs 214 // of the corresponding bits on the managed channels. Each time one of these 215 // states changes, a signal is raised. 216 // TODO: Replace uses of readable() and writable() with 217 // any_channels_readable() and any_channels_writable(). readable()218 bool readable() const { return any_channels_readable(); } writable()219 bool writable() const { return any_channels_writable(); } was_writable()220 bool was_writable() const { return was_writable_; } any_channels_readable()221 bool any_channels_readable() const { 222 return (readable_ == TRANSPORT_STATE_SOME || 223 readable_ == TRANSPORT_STATE_ALL); 224 } any_channels_writable()225 bool any_channels_writable() const { 226 return (writable_ == TRANSPORT_STATE_SOME || 227 writable_ == TRANSPORT_STATE_ALL); 228 } all_channels_readable()229 bool all_channels_readable() const { 230 return (readable_ == TRANSPORT_STATE_ALL); 231 } all_channels_writable()232 bool all_channels_writable() const { 233 return (writable_ == TRANSPORT_STATE_ALL); 234 } 235 sigslot::signal1<Transport*> SignalReadableState; 236 sigslot::signal1<Transport*> SignalWritableState; 237 238 // Returns whether the client has requested the channels to connect. connect_requested()239 bool connect_requested() const { return connect_requested_; } 240 241 void SetIceRole(IceRole role); ice_role()242 IceRole ice_role() const { return ice_role_; } 243 SetIceTiebreaker(uint64 IceTiebreaker)244 void SetIceTiebreaker(uint64 IceTiebreaker) { tiebreaker_ = IceTiebreaker; } IceTiebreaker()245 uint64 IceTiebreaker() { return tiebreaker_; } 246 247 // Must be called before applying local session description. 248 void SetIdentity(talk_base::SSLIdentity* identity); 249 250 // Get a copy of the local identity provided by SetIdentity. 251 bool GetIdentity(talk_base::SSLIdentity** identity); 252 253 // Get a copy of the remote certificate in use by the specified channel. 254 bool GetRemoteCertificate(talk_base::SSLCertificate** cert); 255 protocol()256 TransportProtocol protocol() const { return protocol_; } 257 258 // Create, destroy, and lookup the channels of this type by their components. 259 TransportChannelImpl* CreateChannel(int component); 260 // Note: GetChannel may lead to race conditions, since the mutex is not held 261 // after the pointer is returned. 262 TransportChannelImpl* GetChannel(int component); 263 // Note: HasChannel does not lead to race conditions, unlike GetChannel. HasChannel(int component)264 bool HasChannel(int component) { 265 return (NULL != GetChannel(component)); 266 } 267 bool HasChannels(); 268 void DestroyChannel(int component); 269 270 // Set the local TransportDescription to be used by TransportChannels. 271 // This should be called before ConnectChannels(). 272 bool SetLocalTransportDescription(const TransportDescription& description, 273 ContentAction action); 274 275 // Set the remote TransportDescription to be used by TransportChannels. 276 bool SetRemoteTransportDescription(const TransportDescription& description, 277 ContentAction action); 278 279 // Tells all current and future channels to start connecting. When the first 280 // channel begins connecting, the following signal is raised. 281 void ConnectChannels(); 282 sigslot::signal1<Transport*> SignalConnecting; 283 284 // Resets all of the channels back to their initial state. They are no 285 // longer connecting. 286 void ResetChannels(); 287 288 // Destroys every channel created so far. 289 void DestroyAllChannels(); 290 291 bool GetStats(TransportStats* stats); 292 293 // Before any stanza is sent, the manager will request signaling. Once 294 // signaling is available, the client should call OnSignalingReady. Once 295 // this occurs, the transport (or its channels) can send any waiting stanzas. 296 // OnSignalingReady invokes OnTransportSignalingReady and then forwards this 297 // signal to each channel. 298 sigslot::signal1<Transport*> SignalRequestSignaling; 299 void OnSignalingReady(); 300 301 // Handles sending of ready candidates and receiving of remote candidates. 302 sigslot::signal2<Transport*, 303 const std::vector<Candidate>&> SignalCandidatesReady; 304 305 sigslot::signal1<Transport*> SignalCandidatesAllocationDone; 306 void OnRemoteCandidates(const std::vector<Candidate>& candidates); 307 308 // If candidate is not acceptable, returns false and sets error. 309 // Call this before calling OnRemoteCandidates. 310 virtual bool VerifyCandidate(const Candidate& candidate, 311 std::string* error); 312 313 // Signals when the best connection for a channel changes. 314 sigslot::signal3<Transport*, 315 int, // component 316 const Candidate&> SignalRouteChange; 317 318 // A transport message has generated an transport-specific error. The 319 // stanza that caused the error is available in session_msg. If false is 320 // returned, the error is considered unrecoverable, and the session is 321 // terminated. 322 // TODO(juberti): Remove these obsolete functions once Session no longer 323 // references them. OnTransportError(const buzz::XmlElement * error)324 virtual void OnTransportError(const buzz::XmlElement* error) {} 325 sigslot::signal6<Transport*, const buzz::XmlElement*, const buzz::QName&, 326 const std::string&, const std::string&, 327 const buzz::XmlElement*> 328 SignalTransportError; 329 330 // Forwards the signal from TransportChannel to BaseSession. 331 sigslot::signal0<> SignalRoleConflict; 332 333 virtual bool GetSslRole(talk_base::SSLRole* ssl_role) const; 334 335 protected: 336 // These are called by Create/DestroyChannel above in order to create or 337 // destroy the appropriate type of channel. 338 virtual TransportChannelImpl* CreateTransportChannel(int component) = 0; 339 virtual void DestroyTransportChannel(TransportChannelImpl* channel) = 0; 340 341 // Informs the subclass that we received the signaling ready message. OnTransportSignalingReady()342 virtual void OnTransportSignalingReady() {} 343 344 // The current local transport description, for use by derived classes 345 // when performing transport description negotiation. local_description()346 const TransportDescription* local_description() const { 347 return local_description_.get(); 348 } 349 350 // The current remote transport description, for use by derived classes 351 // when performing transport description negotiation. remote_description()352 const TransportDescription* remote_description() const { 353 return remote_description_.get(); 354 } 355 SetIdentity_w(talk_base::SSLIdentity * identity)356 virtual void SetIdentity_w(talk_base::SSLIdentity* identity) {} 357 GetIdentity_w(talk_base::SSLIdentity ** identity)358 virtual bool GetIdentity_w(talk_base::SSLIdentity** identity) { 359 return false; 360 } 361 362 // Pushes down the transport parameters from the local description, such 363 // as the ICE ufrag and pwd. 364 // Derived classes can override, but must call the base as well. 365 virtual bool ApplyLocalTransportDescription_w(TransportChannelImpl* 366 channel); 367 368 // Pushes down remote ice credentials from the remote description to the 369 // transport channel. 370 virtual bool ApplyRemoteTransportDescription_w(TransportChannelImpl* ch); 371 372 // Negotiates the transport parameters based on the current local and remote 373 // transport description, such at the version of ICE to use, and whether DTLS 374 // should be activated. 375 // Derived classes can negotiate their specific parameters here, but must call 376 // the base as well. 377 virtual bool NegotiateTransportDescription_w(ContentAction local_role); 378 379 // Pushes down the transport parameters obtained via negotiation. 380 // Derived classes can set their specific parameters here, but must call the 381 // base as well. 382 virtual bool ApplyNegotiatedTransportDescription_w( 383 TransportChannelImpl* channel); 384 GetSslRole_w(talk_base::SSLRole * ssl_role)385 virtual bool GetSslRole_w(talk_base::SSLRole* ssl_role) const { 386 return false; 387 } 388 389 private: 390 struct ChannelMapEntry { ChannelMapEntryChannelMapEntry391 ChannelMapEntry() : impl_(NULL), candidates_allocated_(false), ref_(0) {} ChannelMapEntryChannelMapEntry392 explicit ChannelMapEntry(TransportChannelImpl *impl) 393 : impl_(impl), 394 candidates_allocated_(false), 395 ref_(0) { 396 } 397 AddRefChannelMapEntry398 void AddRef() { ++ref_; } DecRefChannelMapEntry399 void DecRef() { 400 ASSERT(ref_ > 0); 401 --ref_; 402 } refChannelMapEntry403 int ref() const { return ref_; } 404 getChannelMapEntry405 TransportChannelImpl* get() const { return impl_; } 406 TransportChannelImpl* operator->() const { return impl_; } set_candidates_allocatedChannelMapEntry407 void set_candidates_allocated(bool status) { 408 candidates_allocated_ = status; 409 } candidates_allocatedChannelMapEntry410 bool candidates_allocated() const { return candidates_allocated_; } 411 412 private: 413 TransportChannelImpl *impl_; 414 bool candidates_allocated_; 415 int ref_; 416 }; 417 418 // Candidate component => ChannelMapEntry 419 typedef std::map<int, ChannelMapEntry> ChannelMap; 420 421 // Called when the state of a channel changes. 422 void OnChannelReadableState(TransportChannel* channel); 423 void OnChannelWritableState(TransportChannel* channel); 424 425 // Called when a channel requests signaling. 426 void OnChannelRequestSignaling(TransportChannelImpl* channel); 427 428 // Called when a candidate is ready from remote peer. 429 void OnRemoteCandidate(const Candidate& candidate); 430 // Called when a candidate is ready from channel. 431 void OnChannelCandidateReady(TransportChannelImpl* channel, 432 const Candidate& candidate); 433 void OnChannelRouteChange(TransportChannel* channel, 434 const Candidate& remote_candidate); 435 void OnChannelCandidatesAllocationDone(TransportChannelImpl* channel); 436 // Called when there is ICE role change. 437 void OnRoleConflict(TransportChannelImpl* channel); 438 439 // Dispatches messages to the appropriate handler (below). 440 void OnMessage(talk_base::Message* msg); 441 442 // These are versions of the above methods that are called only on a 443 // particular thread (s = signaling, w = worker). The above methods post or 444 // send a message to invoke this version. 445 TransportChannelImpl* CreateChannel_w(int component); 446 void DestroyChannel_w(int component); 447 void ConnectChannels_w(); 448 void ResetChannels_w(); 449 void DestroyAllChannels_w(); 450 void OnRemoteCandidate_w(const Candidate& candidate); 451 void OnChannelReadableState_s(); 452 void OnChannelWritableState_s(); 453 void OnChannelRequestSignaling_s(int component); 454 void OnConnecting_s(); 455 void OnChannelRouteChange_s(const TransportChannel* channel, 456 const Candidate& remote_candidate); 457 void OnChannelCandidatesAllocationDone_s(); 458 459 // Helper function that invokes the given function on every channel. 460 typedef void (TransportChannelImpl::* TransportChannelFunc)(); 461 void CallChannels_w(TransportChannelFunc func); 462 463 // Computes the OR of the channel's read or write state (argument picks). 464 TransportState GetTransportState_s(bool read); 465 466 void OnChannelCandidateReady_s(); 467 468 void SetIceRole_w(IceRole role); 469 void SetRemoteIceMode_w(IceMode mode); 470 bool SetLocalTransportDescription_w(const TransportDescription& desc, 471 ContentAction action); 472 bool SetRemoteTransportDescription_w(const TransportDescription& desc, 473 ContentAction action); 474 bool GetStats_w(TransportStats* infos); 475 bool GetRemoteCertificate_w(talk_base::SSLCertificate** cert); 476 477 478 talk_base::Thread* signaling_thread_; 479 talk_base::Thread* worker_thread_; 480 std::string content_name_; 481 std::string type_; 482 PortAllocator* allocator_; 483 bool destroyed_; 484 TransportState readable_; 485 TransportState writable_; 486 bool was_writable_; 487 bool connect_requested_; 488 IceRole ice_role_; 489 uint64 tiebreaker_; 490 TransportProtocol protocol_; 491 IceMode remote_ice_mode_; 492 talk_base::scoped_ptr<TransportDescription> local_description_; 493 talk_base::scoped_ptr<TransportDescription> remote_description_; 494 495 ChannelMap channels_; 496 // Buffers the ready_candidates so that SignalCanidatesReady can 497 // provide them in multiples. 498 std::vector<Candidate> ready_candidates_; 499 // Protects changes to channels and messages 500 talk_base::CriticalSection crit_; 501 502 DISALLOW_EVIL_CONSTRUCTORS(Transport); 503 }; 504 505 // Extract a TransportProtocol from a TransportDescription. 506 TransportProtocol TransportProtocolFromDescription( 507 const TransportDescription* desc); 508 509 } // namespace cricket 510 511 #endif // TALK_P2P_BASE_TRANSPORT_H_ 512