webrtc_m130/p2p/base/turnport.h

326 lines
12 KiB
C
Raw Normal View History

/*
* Copyright 2012 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef P2P_BASE_TURNPORT_H_
#define P2P_BASE_TURNPORT_H_
#include <stdio.h>
#include <list>
#include <set>
#include <string>
#include "p2p/base/port.h"
#include "p2p/client/basicportallocator.h"
#include "rtc_base/asyncinvoker.h"
#include "rtc_base/asyncpacketsocket.h"
namespace rtc {
class AsyncResolver;
class SignalThread;
}
namespace webrtc {
class TurnCustomizer;
}
namespace cricket {
extern const char TURN_PORT_TYPE[];
class TurnAllocateRequest;
class TurnEntry;
class TurnPort : public Port {
public:
enum PortState {
STATE_CONNECTING, // Initial state, cannot send any packets.
STATE_CONNECTED, // Socket connected, ready to send stun requests.
STATE_READY, // Received allocate success, can send any packets.
Reland of Do not delete a connection in the turn port with permission error or refresh error. (patchset #1 id:1 of https://codereview.webrtc.org/2090833002/ ) Reason for revert: The Webrtc waterfall indicates that this revert is not necessary. Original issue's description: > Revert of Do not delete a connection in the turn port with permission error or refresh error. (patchset #6 id:260001 of https://codereview.webrtc.org/2068263003/ ) > > Reason for revert: > It broke webrtc builds. > > Original issue's description: > > Do not delete a connection in the turn port with permission error, refresh error, or binding error. > > > > Even if those error happened, the connection may still be able to receive packets for a while. > > If we delete the connections, all packets arriving will be dropped. > > > > BUG=webrtc:6007 > > R=deadbeef@webrtc.org, pthatcher@webrtc.org > > > > Committed: https://crrev.com/3d77deb29c15bfb8f794ef3413837a0ec0f0c131 > > Cr-Commit-Position: refs/heads/master@{#13262} > > NOPRESUBMIT=true > NOTREECHECKS=true > NOTRY=true > TBR=pthatcher@webrtc.org,deadbeef@webrtc.org > # Not skipping CQ checks because original CL landed more than 1 days ago. > BUG=webrtc:6007 > > Committed: https://crrev.com/3159ffae6b1d5cba2ad972bd3d8074ac85f2c7f9 > Cr-Commit-Position: refs/heads/master@{#13265} TBR=pthatcher@webrtc.org,deadbeef@webrtc.org # Skipping CQ checks because original CL landed less than 1 days ago. NOPRESUBMIT=true NOTREECHECKS=true NOTRY=true BUG=webrtc:6007 Review-Url: https://codereview.webrtc.org/2090073003 Cr-Commit-Position: refs/heads/master@{#13266}
2016-06-22 16:26:29 -07:00
STATE_RECEIVEONLY, // Had REFRESH_REQUEST error, cannot send any packets.
STATE_DISCONNECTED, // TCP connection died, cannot send/receive any
// packets.
};
Make Port (and subclasses) fully "Network"-based, instead of IP-based. For ICE, we want sockets that are bound to specific network interfaces, rather than to specific IP addresses. So, a while ago, we added a "Network" class that gets passed into the Port constructor, in addition to the IP address as before. But we never finished the job of removing the IP address field, such that a Port only guarantees something about the network interface it's associated with, and not the specific IP address it ends up with. This CL does that, and as a consequence, if a port ends up bound to an IP address other than the "best" one (returned by Network::GetBestIP), this *won't* be treated as an error. This is relevant to Android, where even though we pass an IP address into "Bind" as a way of identifying the network, the socket actually gets bound using "android_setsocknetwork", which doesn't provide any guarantees about the IP address. So, if a network interface has multiple IPv6 addresses (for instance), we may not correctly predict the one the OS will choose, and that's ok. This CL also moves "SetAlternateLocalAddress" from VirtualSocket to VirtualSocketServer, which makes for much more readable test code. The next step, if there is one, is to pass along the Network class all the way to SocketServer::Bind. Then the socket server could do smart things with the network information. We could even stick a platform- specific network handle in the Network object, such that the socket server could use it for the binding, or for "sendmsg", for example. See bug 7026 for more context about the sendmsg idea. BUG=webrtc:7715 Review-Url: https://codereview.webrtc.org/2989303002 Cr-Commit-Position: refs/heads/master@{#19251}
2017-08-04 15:01:57 -07:00
// Create a TURN port using the shared UDP socket, |socket|.
static TurnPort* Create(rtc::Thread* thread,
rtc::PacketSocketFactory* factory,
rtc::Network* network,
rtc::AsyncPacketSocket* socket,
const std::string& username, // ice username.
const std::string& password, // ice password.
const ProtocolAddress& server_address,
const RelayCredentials& credentials,
int server_priority,
const std::string& origin,
webrtc::TurnCustomizer* customizer) {
return new TurnPort(thread, factory, network, socket, username, password,
server_address, credentials, server_priority, origin,
customizer);
}
Make Port (and subclasses) fully "Network"-based, instead of IP-based. For ICE, we want sockets that are bound to specific network interfaces, rather than to specific IP addresses. So, a while ago, we added a "Network" class that gets passed into the Port constructor, in addition to the IP address as before. But we never finished the job of removing the IP address field, such that a Port only guarantees something about the network interface it's associated with, and not the specific IP address it ends up with. This CL does that, and as a consequence, if a port ends up bound to an IP address other than the "best" one (returned by Network::GetBestIP), this *won't* be treated as an error. This is relevant to Android, where even though we pass an IP address into "Bind" as a way of identifying the network, the socket actually gets bound using "android_setsocknetwork", which doesn't provide any guarantees about the IP address. So, if a network interface has multiple IPv6 addresses (for instance), we may not correctly predict the one the OS will choose, and that's ok. This CL also moves "SetAlternateLocalAddress" from VirtualSocket to VirtualSocketServer, which makes for much more readable test code. The next step, if there is one, is to pass along the Network class all the way to SocketServer::Bind. Then the socket server could do smart things with the network information. We could even stick a platform- specific network handle in the Network object, such that the socket server could use it for the binding, or for "sendmsg", for example. See bug 7026 for more context about the sendmsg idea. BUG=webrtc:7715 Review-Url: https://codereview.webrtc.org/2989303002 Cr-Commit-Position: refs/heads/master@{#19251}
2017-08-04 15:01:57 -07:00
// Create a TURN port that will use a new socket, bound to |network| and
// using a port in the range between |min_port| and |max_port|.
static TurnPort* Create(rtc::Thread* thread,
rtc::PacketSocketFactory* factory,
rtc::Network* network,
uint16_t min_port,
uint16_t max_port,
const std::string& username, // ice username.
const std::string& password, // ice password.
const ProtocolAddress& server_address,
const RelayCredentials& credentials,
int server_priority,
const std::string& origin,
const std::vector<std::string>& tls_alpn_protocols,
const std::vector<std::string>& tls_elliptic_curves,
webrtc::TurnCustomizer* customizer) {
Make Port (and subclasses) fully "Network"-based, instead of IP-based. For ICE, we want sockets that are bound to specific network interfaces, rather than to specific IP addresses. So, a while ago, we added a "Network" class that gets passed into the Port constructor, in addition to the IP address as before. But we never finished the job of removing the IP address field, such that a Port only guarantees something about the network interface it's associated with, and not the specific IP address it ends up with. This CL does that, and as a consequence, if a port ends up bound to an IP address other than the "best" one (returned by Network::GetBestIP), this *won't* be treated as an error. This is relevant to Android, where even though we pass an IP address into "Bind" as a way of identifying the network, the socket actually gets bound using "android_setsocknetwork", which doesn't provide any guarantees about the IP address. So, if a network interface has multiple IPv6 addresses (for instance), we may not correctly predict the one the OS will choose, and that's ok. This CL also moves "SetAlternateLocalAddress" from VirtualSocket to VirtualSocketServer, which makes for much more readable test code. The next step, if there is one, is to pass along the Network class all the way to SocketServer::Bind. Then the socket server could do smart things with the network information. We could even stick a platform- specific network handle in the Network object, such that the socket server could use it for the binding, or for "sendmsg", for example. See bug 7026 for more context about the sendmsg idea. BUG=webrtc:7715 Review-Url: https://codereview.webrtc.org/2989303002 Cr-Commit-Position: refs/heads/master@{#19251}
2017-08-04 15:01:57 -07:00
return new TurnPort(thread, factory, network, min_port, max_port, username,
password, server_address, credentials, server_priority,
origin, tls_alpn_protocols, tls_elliptic_curves,
customizer);
}
~TurnPort() override;
const ProtocolAddress& server_address() const { return server_address_; }
// Returns an empty address if the local address has not been assigned.
rtc::SocketAddress GetLocalAddress() const;
bool ready() const { return state_ == STATE_READY; }
bool connected() const {
return state_ == STATE_READY || state_ == STATE_CONNECTED;
}
const RelayCredentials& credentials() const { return credentials_; }
ProtocolType GetProtocol() const override;
virtual TlsCertPolicy GetTlsCertPolicy() const;
virtual void SetTlsCertPolicy(TlsCertPolicy tls_cert_policy);
virtual std::vector<std::string> GetTlsAlpnProtocols() const;
virtual std::vector<std::string> GetTlsEllipticCurves() const;
void PrepareAddress() override;
Connection* CreateConnection(const Candidate& c,
PortInterface::CandidateOrigin origin) override;
int SendTo(const void* data,
size_t size,
const rtc::SocketAddress& addr,
const rtc::PacketOptions& options,
bool payload) override;
int SetOption(rtc::Socket::Option opt, int value) override;
int GetOption(rtc::Socket::Option opt, int* value) override;
int GetError() override;
bool HandleIncomingPacket(rtc::AsyncPacketSocket* socket,
const char* data,
size_t size,
const rtc::SocketAddress& remote_addr,
const rtc::PacketTime& packet_time) override;
virtual void OnReadPacket(rtc::AsyncPacketSocket* socket,
const char* data, size_t size,
const rtc::SocketAddress& remote_addr,
const rtc::PacketTime& packet_time);
void OnSentPacket(rtc::AsyncPacketSocket* socket,
const rtc::SentPacket& sent_packet) override;
virtual void OnReadyToSend(rtc::AsyncPacketSocket* socket);
bool SupportsProtocol(const std::string& protocol) const override;
void OnSocketConnect(rtc::AsyncPacketSocket* socket);
void OnSocketClose(rtc::AsyncPacketSocket* socket, int error);
const std::string& hash() const { return hash_; }
const std::string& nonce() const { return nonce_; }
int error() const { return error_; }
void OnAllocateMismatch();
rtc::AsyncPacketSocket* socket() const {
return socket_;
}
// For testing only.
rtc::AsyncInvoker* invoker() { return &invoker_; }
// Signal with resolved server address.
// Parameters are port, server address and resolved server address.
// This signal will be sent only if server address is resolved successfully.
sigslot::signal3<TurnPort*,
const rtc::SocketAddress&,
const rtc::SocketAddress&> SignalResolvedServerAddress;
// All public methods/signals below are for testing only.
sigslot::signal2<TurnPort*, int> SignalTurnRefreshResult;
sigslot::signal3<TurnPort*, const rtc::SocketAddress&, int>
SignalCreatePermissionResult;
void FlushRequests(int msg_type) { request_manager_.Flush(msg_type); }
bool HasRequests() { return !request_manager_.empty(); }
void set_credentials(RelayCredentials& credentials) {
credentials_ = credentials;
}
// Finds the turn entry with |address| and sets its channel id.
// Returns true if the entry is found.
bool SetEntryChannelId(const rtc::SocketAddress& address, int channel_id);
// Visible for testing.
// Shuts down the turn port, usually because of some fatal errors.
void Close();
protected:
TurnPort(rtc::Thread* thread,
rtc::PacketSocketFactory* factory,
rtc::Network* network,
rtc::AsyncPacketSocket* socket,
const std::string& username,
const std::string& password,
const ProtocolAddress& server_address,
const RelayCredentials& credentials,
int server_priority,
const std::string& origin,
webrtc::TurnCustomizer* customizer);
TurnPort(rtc::Thread* thread,
rtc::PacketSocketFactory* factory,
rtc::Network* network,
uint16_t min_port,
uint16_t max_port,
const std::string& username,
const std::string& password,
const ProtocolAddress& server_address,
const RelayCredentials& credentials,
int server_priority,
const std::string& origin,
const std::vector<std::string>& tls_alpn_protocols,
const std::vector<std::string>& tls_elliptic_curves,
webrtc::TurnCustomizer* customizer);
private:
enum {
MSG_ALLOCATE_ERROR = MSG_FIRST_AVAILABLE,
MSG_ALLOCATE_MISMATCH,
MSG_TRY_ALTERNATE_SERVER,
MSG_REFRESH_ERROR
};
typedef std::list<TurnEntry*> EntryList;
typedef std::map<rtc::Socket::Option, int> SocketOptionsMap;
typedef std::set<rtc::SocketAddress> AttemptedServerSet;
void OnMessage(rtc::Message* pmsg) override;
void HandleConnectionDestroyed(Connection* conn) override;
bool CreateTurnClientSocket();
void set_nonce(const std::string& nonce) { nonce_ = nonce; }
void set_realm(const std::string& realm) {
if (realm != realm_) {
realm_ = realm;
UpdateHash();
}
}
Reland of Do not delete a connection in the turn port with permission error or refresh error. (patchset #1 id:1 of https://codereview.webrtc.org/2090833002/ ) Reason for revert: The Webrtc waterfall indicates that this revert is not necessary. Original issue's description: > Revert of Do not delete a connection in the turn port with permission error or refresh error. (patchset #6 id:260001 of https://codereview.webrtc.org/2068263003/ ) > > Reason for revert: > It broke webrtc builds. > > Original issue's description: > > Do not delete a connection in the turn port with permission error, refresh error, or binding error. > > > > Even if those error happened, the connection may still be able to receive packets for a while. > > If we delete the connections, all packets arriving will be dropped. > > > > BUG=webrtc:6007 > > R=deadbeef@webrtc.org, pthatcher@webrtc.org > > > > Committed: https://crrev.com/3d77deb29c15bfb8f794ef3413837a0ec0f0c131 > > Cr-Commit-Position: refs/heads/master@{#13262} > > NOPRESUBMIT=true > NOTREECHECKS=true > NOTRY=true > TBR=pthatcher@webrtc.org,deadbeef@webrtc.org > # Not skipping CQ checks because original CL landed more than 1 days ago. > BUG=webrtc:6007 > > Committed: https://crrev.com/3159ffae6b1d5cba2ad972bd3d8074ac85f2c7f9 > Cr-Commit-Position: refs/heads/master@{#13265} TBR=pthatcher@webrtc.org,deadbeef@webrtc.org # Skipping CQ checks because original CL landed less than 1 days ago. NOPRESUBMIT=true NOTREECHECKS=true NOTRY=true BUG=webrtc:6007 Review-Url: https://codereview.webrtc.org/2090073003 Cr-Commit-Position: refs/heads/master@{#13266}
2016-06-22 16:26:29 -07:00
void OnRefreshError();
void HandleRefreshError();
bool SetAlternateServer(const rtc::SocketAddress& address);
void ResolveTurnAddress(const rtc::SocketAddress& address);
void OnResolveResult(rtc::AsyncResolverInterface* resolver);
void AddRequestAuthInfo(StunMessage* msg);
void OnSendStunPacket(const void* data, size_t size, StunRequest* request);
// Stun address from allocate success response.
// Currently used only for testing.
void OnStunAddress(const rtc::SocketAddress& address);
void OnAllocateSuccess(const rtc::SocketAddress& address,
const rtc::SocketAddress& stun_address);
void OnAllocateError();
void OnAllocateRequestTimeout();
void HandleDataIndication(const char* data, size_t size,
const rtc::PacketTime& packet_time);
void HandleChannelData(int channel_id, const char* data, size_t size,
const rtc::PacketTime& packet_time);
void DispatchPacket(const char* data, size_t size,
const rtc::SocketAddress& remote_addr,
ProtocolType proto, const rtc::PacketTime& packet_time);
bool ScheduleRefresh(int lifetime);
void SendRequest(StunRequest* request, int delay);
int Send(const void* data, size_t size,
const rtc::PacketOptions& options);
void UpdateHash();
bool UpdateNonce(StunMessage* response);
void ResetNonce();
bool HasPermission(const rtc::IPAddress& ipaddr) const;
TurnEntry* FindEntry(const rtc::SocketAddress& address) const;
TurnEntry* FindEntry(int channel_id) const;
bool EntryExists(TurnEntry* e);
void CreateOrRefreshEntry(const rtc::SocketAddress& address);
void DestroyEntry(TurnEntry* entry);
// Destroys the entry only if |timestamp| matches the destruction timestamp
// in |entry|.
void DestroyEntryIfNotCancelled(TurnEntry* entry, int64_t timestamp);
void ScheduleEntryDestruction(TurnEntry* entry);
Reland of Do not delete a connection in the turn port with permission error or refresh error. (patchset #1 id:1 of https://codereview.webrtc.org/2090833002/ ) Reason for revert: The Webrtc waterfall indicates that this revert is not necessary. Original issue's description: > Revert of Do not delete a connection in the turn port with permission error or refresh error. (patchset #6 id:260001 of https://codereview.webrtc.org/2068263003/ ) > > Reason for revert: > It broke webrtc builds. > > Original issue's description: > > Do not delete a connection in the turn port with permission error, refresh error, or binding error. > > > > Even if those error happened, the connection may still be able to receive packets for a while. > > If we delete the connections, all packets arriving will be dropped. > > > > BUG=webrtc:6007 > > R=deadbeef@webrtc.org, pthatcher@webrtc.org > > > > Committed: https://crrev.com/3d77deb29c15bfb8f794ef3413837a0ec0f0c131 > > Cr-Commit-Position: refs/heads/master@{#13262} > > NOPRESUBMIT=true > NOTREECHECKS=true > NOTRY=true > TBR=pthatcher@webrtc.org,deadbeef@webrtc.org > # Not skipping CQ checks because original CL landed more than 1 days ago. > BUG=webrtc:6007 > > Committed: https://crrev.com/3159ffae6b1d5cba2ad972bd3d8074ac85f2c7f9 > Cr-Commit-Position: refs/heads/master@{#13265} TBR=pthatcher@webrtc.org,deadbeef@webrtc.org # Skipping CQ checks because original CL landed less than 1 days ago. NOPRESUBMIT=true NOTREECHECKS=true NOTRY=true BUG=webrtc:6007 Review-Url: https://codereview.webrtc.org/2090073003 Cr-Commit-Position: refs/heads/master@{#13266}
2016-06-22 16:26:29 -07:00
// Marks the connection with remote address |address| failed and
// pruned (a.k.a. write-timed-out). Returns true if a connection is found.
bool FailAndPruneConnection(const rtc::SocketAddress& address);
// Reconstruct the URL of the server which the candidate is gathered from.
std::string ReconstructedServerUrl();
void TurnCustomizerMaybeModifyOutgoingStunMessage(StunMessage* message);
bool TurnCustomizerAllowChannelData(const void* data,
size_t size, bool payload);
ProtocolAddress server_address_;
Add disabled certificate check support to IceServer PeerConnection API. Refactor "OPT_SSLTCP" renaming it to "OPT_TLS_FAKE", making it clear that it's not actually some kind of SSL over TCP. Also making it clear that it's mutually exclusive with OPT_TLS. Maintaining deprecated backwards compatible support for "OPT_SSLTCP". Add "OPT_TLS_INSECURE" that implements the new certificate-check disabled TLS mode, which is also mutually exclusive with the other TLS options. PortAllocator: Add a new TLS policy enum TlsCertPolicy which defines the new insecure mode and added it as a RelayCredentials member. TurnPort: Add new TLS policy member with appropriate getter and setter to avoid constructor bloat. Initialize it from the RelayCredentials after the TurnPort is created. Expose the new feature in the PeerConnection API via IceServer.tls_certificate_policy as well as via the Android JNI PeerConnection API. For security reasons we ensure that: 1) The policy is always explicitly initialized to secure. 2) API users have to explicitly integrate with the feature to use it, and will otherwise get no change in behavior. 3) The feature is not immediately exposed in non-native contexts. For example, disabling of certificate validation is not implemented via URI parsing since this would immediately allow it to be used from a web page. This is a second attempt of https://codereview.webrtc.org/2557803002/ which was rolled back in https://codereview.webrtc.org/2590153002/ BUG=webrtc:6840 Review-Url: https://codereview.webrtc.org/2594623002 Cr-Commit-Position: refs/heads/master@{#15967}
2017-01-09 08:35:45 -08:00
TlsCertPolicy tls_cert_policy_ = TlsCertPolicy::TLS_CERT_POLICY_SECURE;
std::vector<std::string> tls_alpn_protocols_;
std::vector<std::string> tls_elliptic_curves_;
RelayCredentials credentials_;
AttemptedServerSet attempted_server_addresses_;
rtc::AsyncPacketSocket* socket_;
SocketOptionsMap socket_options_;
rtc::AsyncResolverInterface* resolver_;
int error_;
StunRequestManager request_manager_;
std::string realm_; // From 401/438 response message.
std::string nonce_; // From 401/438 response message.
std::string hash_; // Digest of username:realm:password
int next_channel_number_;
EntryList entries_;
PortState state_;
// By default the value will be set to 0. This value will be used in
// calculating the candidate priority.
int server_priority_;
// The number of retries made due to allocate mismatch error.
size_t allocate_mismatch_retries_;
rtc::AsyncInvoker invoker_;
// Optional TurnCustomizer that can modify outgoing messages.
webrtc::TurnCustomizer *turn_customizer_ = nullptr;
friend class TurnEntry;
friend class TurnAllocateRequest;
friend class TurnRefreshRequest;
friend class TurnCreatePermissionRequest;
friend class TurnChannelBindRequest;
};
} // namespace cricket
#endif // P2P_BASE_TURNPORT_H_