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 #ifndef TALK_P2P_BASE_PORT_H_ 29 #define TALK_P2P_BASE_PORT_H_ 30 31 #include <string> 32 #include <vector> 33 #include <map> 34 35 #include "talk/base/asyncpacketsocket.h" 36 #include "talk/base/network.h" 37 #include "talk/base/proxyinfo.h" 38 #include "talk/base/ratetracker.h" 39 #include "talk/base/sigslot.h" 40 #include "talk/base/socketaddress.h" 41 #include "talk/base/thread.h" 42 #include "talk/p2p/base/candidate.h" 43 #include "talk/p2p/base/packetsocketfactory.h" 44 #include "talk/p2p/base/portinterface.h" 45 #include "talk/p2p/base/stun.h" 46 #include "talk/p2p/base/stunrequest.h" 47 #include "talk/p2p/base/transport.h" 48 49 namespace cricket { 50 51 class Connection; 52 class ConnectionRequest; 53 54 extern const char LOCAL_PORT_TYPE[]; 55 extern const char STUN_PORT_TYPE[]; 56 extern const char PRFLX_PORT_TYPE[]; 57 extern const char RELAY_PORT_TYPE[]; 58 59 extern const char UDP_PROTOCOL_NAME[]; 60 extern const char TCP_PROTOCOL_NAME[]; 61 extern const char SSLTCP_PROTOCOL_NAME[]; 62 63 // The length of time we wait before timing out readability on a connection. 64 const uint32 CONNECTION_READ_TIMEOUT = 30 * 1000; // 30 seconds 65 66 // The length of time we wait before timing out writability on a connection. 67 const uint32 CONNECTION_WRITE_TIMEOUT = 15 * 1000; // 15 seconds 68 69 // The length of time we wait before we become unwritable. 70 const uint32 CONNECTION_WRITE_CONNECT_TIMEOUT = 5 * 1000; // 5 seconds 71 72 // The number of pings that must fail to respond before we become unwritable. 73 const uint32 CONNECTION_WRITE_CONNECT_FAILURES = 5; 74 75 // This is the length of time that we wait for a ping response to come back. 76 const int CONNECTION_RESPONSE_TIMEOUT = 5 * 1000; // 5 seconds 77 78 enum RelayType { 79 RELAY_GTURN, // Legacy google relay service. 80 RELAY_TURN // Standard (TURN) relay service. 81 }; 82 83 enum IcePriorityValue { 84 // The reason we are choosing Relay preference 2 is because, we can run 85 // Relay from client to server on UDP/TCP/TLS. To distinguish the transport 86 // protocol, we prefer UDP over TCP over TLS. 87 // For UDP ICE_TYPE_PREFERENCE_RELAY will be 2. 88 // For TCP ICE_TYPE_PREFERENCE_RELAY will be 1. 89 // For TLS ICE_TYPE_PREFERENCE_RELAY will be 0. 90 // Check turnport.cc for setting these values. 91 ICE_TYPE_PREFERENCE_RELAY = 2, 92 ICE_TYPE_PREFERENCE_HOST_TCP = 90, 93 ICE_TYPE_PREFERENCE_SRFLX = 100, 94 ICE_TYPE_PREFERENCE_PRFLX = 110, 95 ICE_TYPE_PREFERENCE_HOST = 126 96 }; 97 98 const char* ProtoToString(ProtocolType proto); 99 bool StringToProto(const char* value, ProtocolType* proto); 100 101 struct ProtocolAddress { 102 talk_base::SocketAddress address; 103 ProtocolType proto; 104 bool secure; 105 106 ProtocolAddress(const talk_base::SocketAddress& a, ProtocolType p) 107 : address(a), proto(p), secure(false) { } 108 ProtocolAddress(const talk_base::SocketAddress& a, ProtocolType p, bool sec) 109 : address(a), proto(p), secure(sec) { } 110 }; 111 112 // Represents a local communication mechanism that can be used to create 113 // connections to similar mechanisms of the other client. Subclasses of this 114 // one add support for specific mechanisms like local UDP ports. 115 class Port : public PortInterface, public talk_base::MessageHandler, 116 public sigslot::has_slots<> { 117 public: 118 Port(talk_base::Thread* thread, talk_base::PacketSocketFactory* factory, 119 talk_base::Network* network, const talk_base::IPAddress& ip, 120 const std::string& username_fragment, const std::string& password); 121 Port(talk_base::Thread* thread, const std::string& type, 122 talk_base::PacketSocketFactory* factory, 123 talk_base::Network* network, const talk_base::IPAddress& ip, 124 int min_port, int max_port, const std::string& username_fragment, 125 const std::string& password); 126 virtual ~Port(); 127 128 virtual const std::string& Type() const { return type_; } 129 virtual talk_base::Network* Network() const { return network_; } 130 131 // This method will set the flag which enables standard ICE/STUN procedures 132 // in STUN connectivity checks. Currently this method does 133 // 1. Add / Verify MI attribute in STUN binding requests. 134 // 2. Username attribute in STUN binding request will be RFRAF:LFRAG, 135 // as opposed to RFRAGLFRAG. 136 virtual void SetIceProtocolType(IceProtocolType protocol) { 137 ice_protocol_ = protocol; 138 } 139 virtual IceProtocolType IceProtocol() const { return ice_protocol_; } 140 141 // Methods to set/get ICE role and tiebreaker values. 142 IceRole GetIceRole() const { return ice_role_; } 143 void SetIceRole(IceRole role) { ice_role_ = role; } 144 145 void SetIceTiebreaker(uint64 tiebreaker) { tiebreaker_ = tiebreaker; } 146 uint64 IceTiebreaker() const { return tiebreaker_; } 147 148 virtual bool SharedSocket() const { return shared_socket_; } 149 150 // The thread on which this port performs its I/O. 151 talk_base::Thread* thread() { return thread_; } 152 153 // The factory used to create the sockets of this port. 154 talk_base::PacketSocketFactory* socket_factory() const { return factory_; } 155 void set_socket_factory(talk_base::PacketSocketFactory* factory) { 156 factory_ = factory; 157 } 158 159 // For debugging purposes. 160 const std::string& content_name() const { return content_name_; } 161 void set_content_name(const std::string& content_name) { 162 content_name_ = content_name; 163 } 164 165 int component() const { return component_; } 166 void set_component(int component) { component_ = component; } 167 168 bool send_retransmit_count_attribute() const { 169 return send_retransmit_count_attribute_; 170 } 171 void set_send_retransmit_count_attribute(bool enable) { 172 send_retransmit_count_attribute_ = enable; 173 } 174 175 // Identifies the generation that this port was created in. 176 uint32 generation() { return generation_; } 177 void set_generation(uint32 generation) { generation_ = generation; } 178 179 // ICE requires a single username/password per content/media line. So the 180 // |ice_username_fragment_| of the ports that belongs to the same content will 181 // be the same. However this causes a small complication with our relay 182 // server, which expects different username for RTP and RTCP. 183 // 184 // To resolve this problem, we implemented the username_fragment(), 185 // which returns a different username (calculated from 186 // |ice_username_fragment_|) for RTCP in the case of ICEPROTO_GOOGLE. And the 187 // username_fragment() simply returns |ice_username_fragment_| when running 188 // in ICEPROTO_RFC5245. 189 // 190 // As a result the ICEPROTO_GOOGLE will use different usernames for RTP and 191 // RTCP. And the ICEPROTO_RFC5245 will use same username for both RTP and 192 // RTCP. 193 const std::string username_fragment() const; 194 const std::string& password() const { return password_; } 195 196 // Fired when candidates are discovered by the port. When all candidates 197 // are discovered that belong to port SignalAddressReady is fired. 198 sigslot::signal2<Port*, const Candidate&> SignalCandidateReady; 199 200 // Provides all of the above information in one handy object. 201 virtual const std::vector<Candidate>& Candidates() const { 202 return candidates_; 203 } 204 205 // SignalPortComplete is sent when port completes the task of candidates 206 // allocation. 207 sigslot::signal1<Port*> SignalPortComplete; 208 // This signal sent when port fails to allocate candidates and this port 209 // can't be used in establishing the connections. When port is in shared mode 210 // and port fails to allocate one of the candidates, port shouldn't send 211 // this signal as other candidates might be usefull in establishing the 212 // connection. 213 sigslot::signal1<Port*> SignalPortError; 214 215 // Returns a map containing all of the connections of this port, keyed by the 216 // remote address. 217 typedef std::map<talk_base::SocketAddress, Connection*> AddressMap; 218 const AddressMap& connections() { return connections_; } 219 220 // Returns the connection to the given address or NULL if none exists. 221 virtual Connection* GetConnection( 222 const talk_base::SocketAddress& remote_addr); 223 224 // Called each time a connection is created. 225 sigslot::signal2<Port*, Connection*> SignalConnectionCreated; 226 227 // In a shared socket mode each port which shares the socket will decide 228 // to accept the packet based on the |remote_addr|. Currently only UDP 229 // port implemented this method. 230 // TODO(mallinath) - Make it pure virtual. 231 virtual bool HandleIncomingPacket( 232 talk_base::AsyncPacketSocket* socket, const char* data, size_t size, 233 const talk_base::SocketAddress& remote_addr, 234 const talk_base::PacketTime& packet_time) { 235 ASSERT(false); 236 return false; 237 } 238 239 // Sends a response message (normal or error) to the given request. One of 240 // these methods should be called as a response to SignalUnknownAddress. 241 // NOTE: You MUST call CreateConnection BEFORE SendBindingResponse. 242 virtual void SendBindingResponse(StunMessage* request, 243 const talk_base::SocketAddress& addr); 244 virtual void SendBindingErrorResponse( 245 StunMessage* request, const talk_base::SocketAddress& addr, 246 int error_code, const std::string& reason); 247 248 void set_proxy(const std::string& user_agent, 249 const talk_base::ProxyInfo& proxy) { 250 user_agent_ = user_agent; 251 proxy_ = proxy; 252 } 253 const std::string& user_agent() { return user_agent_; } 254 const talk_base::ProxyInfo& proxy() { return proxy_; } 255 256 virtual void EnablePortPackets(); 257 258 // Called if the port has no connections and is no longer useful. 259 void Destroy(); 260 261 virtual void OnMessage(talk_base::Message *pmsg); 262 263 // Debugging description of this port 264 virtual std::string ToString() const; 265 talk_base::IPAddress& ip() { return ip_; } 266 int min_port() { return min_port_; } 267 int max_port() { return max_port_; } 268 269 // Timeout shortening function to speed up unit tests. 270 void set_timeout_delay(int delay) { timeout_delay_ = delay; } 271 272 // This method will return local and remote username fragements from the 273 // stun username attribute if present. 274 bool ParseStunUsername(const StunMessage* stun_msg, 275 std::string* local_username, 276 std::string* remote_username, 277 IceProtocolType* remote_protocol_type) const; 278 void CreateStunUsername(const std::string& remote_username, 279 std::string* stun_username_attr_str) const; 280 281 bool MaybeIceRoleConflict(const talk_base::SocketAddress& addr, 282 IceMessage* stun_msg, 283 const std::string& remote_ufrag); 284 285 // Called when the socket is currently able to send. 286 void OnReadyToSend(); 287 288 // Called when the Connection discovers a local peer reflexive candidate. 289 // Returns the index of the new local candidate. 290 size_t AddPrflxCandidate(const Candidate& local); 291 292 // Returns if RFC 5245 ICE protocol is used. 293 bool IsStandardIce() const; 294 295 // Returns if Google ICE protocol is used. 296 bool IsGoogleIce() const; 297 298 // Returns if Hybrid ICE protocol is used. 299 bool IsHybridIce() const; 300 301 protected: 302 enum { 303 MSG_CHECKTIMEOUT = 0, 304 MSG_FIRST_AVAILABLE 305 }; 306 307 void set_type(const std::string& type) { type_ = type; } 308 // Fills in the local address of the port. 309 void AddAddress(const talk_base::SocketAddress& address, 310 const talk_base::SocketAddress& base_address, 311 const talk_base::SocketAddress& related_address, 312 const std::string& protocol, const std::string& type, 313 uint32 type_preference, bool final); 314 315 // Adds the given connection to the list. (Deleting removes them.) 316 void AddConnection(Connection* conn); 317 318 // Called when a packet is received from an unknown address that is not 319 // currently a connection. If this is an authenticated STUN binding request, 320 // then we will signal the client. 321 void OnReadPacket(const char* data, size_t size, 322 const talk_base::SocketAddress& addr, 323 ProtocolType proto); 324 325 // If the given data comprises a complete and correct STUN message then the 326 // return value is true, otherwise false. If the message username corresponds 327 // with this port's username fragment, msg will contain the parsed STUN 328 // message. Otherwise, the function may send a STUN response internally. 329 // remote_username contains the remote fragment of the STUN username. 330 bool GetStunMessage(const char* data, size_t size, 331 const talk_base::SocketAddress& addr, 332 IceMessage** out_msg, std::string* out_username); 333 334 // Checks if the address in addr is compatible with the port's ip. 335 bool IsCompatibleAddress(const talk_base::SocketAddress& addr); 336 337 // Returns default DSCP value. 338 talk_base::DiffServCodePoint DefaultDscpValue() const { 339 // No change from what MediaChannel set. 340 return talk_base::DSCP_NO_CHANGE; 341 } 342 343 private: 344 void Construct(); 345 // Called when one of our connections deletes itself. 346 void OnConnectionDestroyed(Connection* conn); 347 348 // Checks if this port is useless, and hence, should be destroyed. 349 void CheckTimeout(); 350 351 talk_base::Thread* thread_; 352 talk_base::PacketSocketFactory* factory_; 353 std::string type_; 354 bool send_retransmit_count_attribute_; 355 talk_base::Network* network_; 356 talk_base::IPAddress ip_; 357 int min_port_; 358 int max_port_; 359 std::string content_name_; 360 int component_; 361 uint32 generation_; 362 // In order to establish a connection to this Port (so that real data can be 363 // sent through), the other side must send us a STUN binding request that is 364 // authenticated with this username_fragment and password. 365 // PortAllocatorSession will provide these username_fragment and password. 366 // 367 // Note: we should always use username_fragment() instead of using 368 // |ice_username_fragment_| directly. For the details see the comment on 369 // username_fragment(). 370 std::string ice_username_fragment_; 371 std::string password_; 372 std::vector<Candidate> candidates_; 373 AddressMap connections_; 374 int timeout_delay_; 375 bool enable_port_packets_; 376 IceProtocolType ice_protocol_; 377 IceRole ice_role_; 378 uint64 tiebreaker_; 379 bool shared_socket_; 380 // Information to use when going through a proxy. 381 std::string user_agent_; 382 talk_base::ProxyInfo proxy_; 383 384 friend class Connection; 385 }; 386 387 // Represents a communication link between a port on the local client and a 388 // port on the remote client. 389 class Connection : public talk_base::MessageHandler, 390 public sigslot::has_slots<> { 391 public: 392 // States are from RFC 5245. http://tools.ietf.org/html/rfc5245#section-5.7.4 393 enum State { 394 STATE_WAITING = 0, // Check has not been performed, Waiting pair on CL. 395 STATE_INPROGRESS, // Check has been sent, transaction is in progress. 396 STATE_SUCCEEDED, // Check already done, produced a successful result. 397 STATE_FAILED // Check for this connection failed. 398 }; 399 400 virtual ~Connection(); 401 402 // The local port where this connection sends and receives packets. 403 Port* port() { return port_; } 404 const Port* port() const { return port_; } 405 406 // Returns the description of the local port 407 virtual const Candidate& local_candidate() const; 408 409 // Returns the description of the remote port to which we communicate. 410 const Candidate& remote_candidate() const { return remote_candidate_; } 411 412 // Returns the pair priority. 413 uint64 priority() const; 414 415 enum ReadState { 416 STATE_READ_INIT = 0, // we have yet to receive a ping 417 STATE_READABLE = 1, // we have received pings recently 418 STATE_READ_TIMEOUT = 2, // we haven't received pings in a while 419 }; 420 421 ReadState read_state() const { return read_state_; } 422 bool readable() const { return read_state_ == STATE_READABLE; } 423 424 enum WriteState { 425 STATE_WRITABLE = 0, // we have received ping responses recently 426 STATE_WRITE_UNRELIABLE = 1, // we have had a few ping failures 427 STATE_WRITE_INIT = 2, // we have yet to receive a ping response 428 STATE_WRITE_TIMEOUT = 3, // we have had a large number of ping failures 429 }; 430 431 WriteState write_state() const { return write_state_; } 432 bool writable() const { return write_state_ == STATE_WRITABLE; } 433 434 // Determines whether the connection has finished connecting. This can only 435 // be false for TCP connections. 436 bool connected() const { return connected_; } 437 438 // Estimate of the round-trip time over this connection. 439 uint32 rtt() const { return rtt_; } 440 441 size_t sent_total_bytes(); 442 size_t sent_bytes_second(); 443 size_t recv_total_bytes(); 444 size_t recv_bytes_second(); 445 sigslot::signal1<Connection*> SignalStateChange; 446 447 // Sent when the connection has decided that it is no longer of value. It 448 // will delete itself immediately after this call. 449 sigslot::signal1<Connection*> SignalDestroyed; 450 451 // The connection can send and receive packets asynchronously. This matches 452 // the interface of AsyncPacketSocket, which may use UDP or TCP under the 453 // covers. 454 virtual int Send(const void* data, size_t size, 455 const talk_base::PacketOptions& options) = 0; 456 457 // Error if Send() returns < 0 458 virtual int GetError() = 0; 459 460 sigslot::signal4<Connection*, const char*, size_t, 461 const talk_base::PacketTime&> SignalReadPacket; 462 463 sigslot::signal1<Connection*> SignalReadyToSend; 464 465 // Called when a packet is received on this connection. 466 void OnReadPacket(const char* data, size_t size, 467 const talk_base::PacketTime& packet_time); 468 469 // Called when the socket is currently able to send. 470 void OnReadyToSend(); 471 472 // Called when a connection is determined to be no longer useful to us. We 473 // still keep it around in case the other side wants to use it. But we can 474 // safely stop pinging on it and we can allow it to time out if the other 475 // side stops using it as well. 476 bool pruned() const { return pruned_; } 477 void Prune(); 478 479 bool use_candidate_attr() const { return use_candidate_attr_; } 480 void set_use_candidate_attr(bool enable); 481 482 void set_remote_ice_mode(IceMode mode) { 483 remote_ice_mode_ = mode; 484 } 485 486 // Makes the connection go away. 487 void Destroy(); 488 489 // Checks that the state of this connection is up-to-date. The argument is 490 // the current time, which is compared against various timeouts. 491 void UpdateState(uint32 now); 492 493 // Called when this connection should try checking writability again. 494 uint32 last_ping_sent() const { return last_ping_sent_; } 495 void Ping(uint32 now); 496 497 // Called whenever a valid ping is received on this connection. This is 498 // public because the connection intercepts the first ping for us. 499 uint32 last_ping_received() const { return last_ping_received_; } 500 void ReceivedPing(); 501 502 // Debugging description of this connection 503 std::string ToString() const; 504 std::string ToSensitiveString() const; 505 506 bool reported() const { return reported_; } 507 void set_reported(bool reported) { reported_ = reported;} 508 509 // This flag will be set if this connection is the chosen one for media 510 // transmission. This connection will send STUN ping with USE-CANDIDATE 511 // attribute. 512 sigslot::signal1<Connection*> SignalUseCandidate; 513 // Invoked when Connection receives STUN error response with 487 code. 514 void HandleRoleConflictFromPeer(); 515 516 State state() const { return state_; } 517 518 IceMode remote_ice_mode() const { return remote_ice_mode_; } 519 520 protected: 521 // Constructs a new connection to the given remote port. 522 Connection(Port* port, size_t index, const Candidate& candidate); 523 524 // Called back when StunRequestManager has a stun packet to send 525 void OnSendStunPacket(const void* data, size_t size, StunRequest* req); 526 527 // Callbacks from ConnectionRequest 528 void OnConnectionRequestResponse(ConnectionRequest* req, 529 StunMessage* response); 530 void OnConnectionRequestErrorResponse(ConnectionRequest* req, 531 StunMessage* response); 532 void OnConnectionRequestTimeout(ConnectionRequest* req); 533 534 // Changes the state and signals if necessary. 535 void set_read_state(ReadState value); 536 void set_write_state(WriteState value); 537 void set_state(State state); 538 void set_connected(bool value); 539 540 // Checks if this connection is useless, and hence, should be destroyed. 541 void CheckTimeout(); 542 543 void OnMessage(talk_base::Message *pmsg); 544 545 Port* port_; 546 size_t local_candidate_index_; 547 Candidate remote_candidate_; 548 ReadState read_state_; 549 WriteState write_state_; 550 bool connected_; 551 bool pruned_; 552 // By default |use_candidate_attr_| flag will be true, 553 // as we will be using agrressive nomination. 554 // But when peer is ice-lite, this flag "must" be initialized to false and 555 // turn on when connection becomes "best connection". 556 bool use_candidate_attr_; 557 IceMode remote_ice_mode_; 558 StunRequestManager requests_; 559 uint32 rtt_; 560 uint32 last_ping_sent_; // last time we sent a ping to the other side 561 uint32 last_ping_received_; // last time we received a ping from the other 562 // side 563 uint32 last_data_received_; 564 uint32 last_ping_response_received_; 565 std::vector<uint32> pings_since_last_response_; 566 567 talk_base::RateTracker recv_rate_tracker_; 568 talk_base::RateTracker send_rate_tracker_; 569 570 private: 571 void MaybeAddPrflxCandidate(ConnectionRequest* request, 572 StunMessage* response); 573 574 bool reported_; 575 State state_; 576 577 friend class Port; 578 friend class ConnectionRequest; 579 }; 580 581 // ProxyConnection defers all the interesting work to the port 582 class ProxyConnection : public Connection { 583 public: 584 ProxyConnection(Port* port, size_t index, const Candidate& candidate); 585 586 virtual int Send(const void* data, size_t size, 587 const talk_base::PacketOptions& options); 588 virtual int GetError() { return error_; } 589 590 private: 591 int error_; 592 }; 593 594 } // namespace cricket 595 596 #endif // TALK_P2P_BASE_PORT_H_ 597