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 #include "talk/p2p/base/stunport.h"
30 #include "talk/base/common.h"
31 #include "talk/base/logging.h"
32 #include "talk/base/helpers.h"
33 #include "talk/base/nethelpers.h"
34 #include "talk/p2p/base/common.h"
35 #include "talk/p2p/base/stun.h"
39 // TODO: Move these to a common place (used in relayport too)
40 const int KEEPALIVE_DELAY = 10 * 1000; // 10 seconds - sort timeouts
41 const int RETRY_DELAY = 50; // 50ms, from ICE spec
42 const int RETRY_TIMEOUT = 50 * 1000; // ICE says 50 secs
44 // Handles a binding request sent to the STUN server.
45 class StunBindingRequest : public StunRequest {
47 StunBindingRequest(UDPPort* port, bool keep_alive,
48 const talk_base::SocketAddress& addr)
49 : port_(port), keep_alive_(keep_alive), server_addr_(addr) {
50 start_time_ = talk_base::Time();
53 virtual ~StunBindingRequest() {
56 const talk_base::SocketAddress& server_addr() const { return server_addr_; }
58 virtual void Prepare(StunMessage* request) {
59 request->SetType(STUN_BINDING_REQUEST);
62 virtual void OnResponse(StunMessage* response) {
63 const StunAddressAttribute* addr_attr =
64 response->GetAddress(STUN_ATTR_MAPPED_ADDRESS);
66 LOG(LS_ERROR) << "Binding response missing mapped address.";
67 } else if (addr_attr->family() != STUN_ADDRESS_IPV4 &&
68 addr_attr->family() != STUN_ADDRESS_IPV6) {
69 LOG(LS_ERROR) << "Binding address has bad family";
71 talk_base::SocketAddress addr(addr_attr->ipaddr(), addr_attr->port());
72 port_->OnStunBindingRequestSucceeded(addr);
75 // We will do a keep-alive regardless of whether this request suceeds.
76 // This should have almost no impact on network usage.
78 port_->requests_.SendDelayed(
79 new StunBindingRequest(port_, true, server_addr_),
80 port_->stun_keepalive_delay());
84 virtual void OnErrorResponse(StunMessage* response) {
85 const StunErrorCodeAttribute* attr = response->GetErrorCode();
87 LOG(LS_ERROR) << "Bad allocate response error code";
89 LOG(LS_ERROR) << "Binding error response:"
90 << " class=" << attr->eclass()
91 << " number=" << attr->number()
92 << " reason='" << attr->reason() << "'";
95 port_->OnStunBindingOrResolveRequestFailed();
98 && (talk_base::TimeSince(start_time_) <= RETRY_TIMEOUT)) {
99 port_->requests_.SendDelayed(
100 new StunBindingRequest(port_, true, server_addr_),
101 port_->stun_keepalive_delay());
105 virtual void OnTimeout() {
106 LOG(LS_ERROR) << "Binding request timed out from "
107 << port_->GetLocalAddress().ToSensitiveString()
108 << " (" << port_->Network()->name() << ")";
110 port_->OnStunBindingOrResolveRequestFailed();
113 && (talk_base::TimeSince(start_time_) <= RETRY_TIMEOUT)) {
114 port_->requests_.SendDelayed(
115 new StunBindingRequest(port_, true, server_addr_),
123 talk_base::SocketAddress server_addr_;
127 UDPPort::UDPPort(talk_base::Thread* thread,
128 talk_base::PacketSocketFactory* factory,
129 talk_base::Network* network,
130 talk_base::AsyncPacketSocket* socket,
131 const std::string& username, const std::string& password)
132 : Port(thread, factory, network, socket->GetLocalAddress().ipaddr(),
139 stun_keepalive_delay_(KEEPALIVE_DELAY) {
142 UDPPort::UDPPort(talk_base::Thread* thread,
143 talk_base::PacketSocketFactory* factory,
144 talk_base::Network* network,
145 const talk_base::IPAddress& ip, int min_port, int max_port,
146 const std::string& username, const std::string& password)
147 : Port(thread, LOCAL_PORT_TYPE, factory, network, ip, min_port, max_port,
154 stun_keepalive_delay_(KEEPALIVE_DELAY) {
157 bool UDPPort::Init() {
158 if (!SharedSocket()) {
159 ASSERT(socket_ == NULL);
160 socket_ = socket_factory()->CreateUdpSocket(
161 talk_base::SocketAddress(ip(), 0), min_port(), max_port());
163 LOG_J(LS_WARNING, this) << "UDP socket creation failed";
166 socket_->SignalReadPacket.connect(this, &UDPPort::OnReadPacket);
168 socket_->SignalReadyToSend.connect(this, &UDPPort::OnReadyToSend);
169 socket_->SignalAddressReady.connect(this, &UDPPort::OnLocalAddressReady);
170 requests_.SignalSendPacket.connect(this, &UDPPort::OnSendPacket);
174 UDPPort::~UDPPort() {
176 resolver_->Destroy(false);
182 void UDPPort::PrepareAddress() {
183 ASSERT(requests_.empty());
184 if (socket_->GetState() == talk_base::AsyncPacketSocket::STATE_BOUND) {
185 OnLocalAddressReady(socket_, socket_->GetLocalAddress());
189 void UDPPort::MaybePrepareStunCandidate() {
190 // Sending binding request to the STUN server if address is available to
191 // prepare STUN candidate.
192 if (!server_addr_.IsNil()) {
193 SendStunBindingRequest();
195 // Processing host candidate address.
200 Connection* UDPPort::CreateConnection(const Candidate& address,
201 CandidateOrigin origin) {
202 if (address.protocol() != "udp")
205 if (!IsCompatibleAddress(address.address())) {
209 if (SharedSocket() && Candidates()[0].type() != LOCAL_PORT_TYPE) {
214 Connection* conn = new ProxyConnection(this, 0, address);
219 int UDPPort::SendTo(const void* data, size_t size,
220 const talk_base::SocketAddress& addr,
221 const talk_base::PacketOptions& options,
223 int sent = socket_->SendTo(data, size, addr, options);
225 error_ = socket_->GetError();
226 LOG_J(LS_ERROR, this) << "UDP send of " << size
227 << " bytes failed with error " << error_;
232 int UDPPort::SetOption(talk_base::Socket::Option opt, int value) {
233 return socket_->SetOption(opt, value);
236 int UDPPort::GetOption(talk_base::Socket::Option opt, int* value) {
237 return socket_->GetOption(opt, value);
240 int UDPPort::GetError() {
244 void UDPPort::OnLocalAddressReady(talk_base::AsyncPacketSocket* socket,
245 const talk_base::SocketAddress& address) {
246 AddAddress(address, address, UDP_PROTOCOL_NAME, LOCAL_PORT_TYPE,
247 ICE_TYPE_PREFERENCE_HOST, false);
248 MaybePrepareStunCandidate();
251 void UDPPort::OnReadPacket(
252 talk_base::AsyncPacketSocket* socket, const char* data, size_t size,
253 const talk_base::SocketAddress& remote_addr,
254 const talk_base::PacketTime& packet_time) {
255 ASSERT(socket == socket_);
257 // Look for a response from the STUN server.
258 // Even if the response doesn't match one of our outstanding requests, we
259 // will eat it because it might be a response to a retransmitted packet, and
260 // we already cleared the request when we got the first response.
261 if (!server_addr_.IsUnresolved() && remote_addr == server_addr_) {
262 requests_.CheckResponse(data, size);
266 if (Connection* conn = GetConnection(remote_addr)) {
267 conn->OnReadPacket(data, size, packet_time);
269 Port::OnReadPacket(data, size, remote_addr, PROTO_UDP);
273 void UDPPort::OnReadyToSend(talk_base::AsyncPacketSocket* socket) {
274 Port::OnReadyToSend();
277 void UDPPort::SendStunBindingRequest() {
278 // We will keep pinging the stun server to make sure our NAT pin-hole stays
279 // open during the call.
280 // TODO: Support multiple stun servers, or make ResolveStunAddress find a
281 // server with the correct family, or something similar.
282 ASSERT(requests_.empty());
283 if (server_addr_.IsUnresolved()) {
284 ResolveStunAddress();
285 } else if (socket_->GetState() == talk_base::AsyncPacketSocket::STATE_BOUND) {
286 // Check if |server_addr_| is compatible with the port's ip.
287 if (IsCompatibleAddress(server_addr_)) {
288 requests_.Send(new StunBindingRequest(this, true, server_addr_));
290 // Since we can't send stun messages to the server, we should mark this
292 OnStunBindingOrResolveRequestFailed();
297 void UDPPort::ResolveStunAddress() {
301 resolver_ = socket_factory()->CreateAsyncResolver();
302 resolver_->SignalDone.connect(this, &UDPPort::OnResolveResult);
303 resolver_->Start(server_addr_);
306 void UDPPort::OnResolveResult(talk_base::AsyncResolverInterface* resolver) {
307 ASSERT(resolver == resolver_);
308 if (resolver_->GetError() != 0 ||
309 !resolver_->GetResolvedAddress(ip().family(), &server_addr_)) {
310 LOG_J(LS_WARNING, this) << "StunPort: stun host lookup received error "
311 << resolver_->GetError();
312 OnStunBindingOrResolveRequestFailed();
316 SendStunBindingRequest();
319 void UDPPort::OnStunBindingRequestSucceeded(
320 const talk_base::SocketAddress& stun_addr) {
321 if (ready_) // Discarding the binding response if port is already enabled.
324 if (!SharedSocket() || stun_addr != socket_->GetLocalAddress()) {
325 // If socket is shared and |stun_addr| is equal to local socket
326 // address then discarding the stun address.
327 // Setting related address before STUN candidate is added. For STUN
328 // related address is local socket address.
329 set_related_address(socket_->GetLocalAddress());
330 AddAddress(stun_addr, socket_->GetLocalAddress(), UDP_PROTOCOL_NAME,
331 STUN_PORT_TYPE, ICE_TYPE_PREFERENCE_SRFLX, false);
336 void UDPPort::OnStunBindingOrResolveRequestFailed() {
337 if (ready_) // Discarding failure response if port is already enabled.
340 // If socket is shared, we should process local udp candidate.
341 SetResult(SharedSocket());
344 void UDPPort::SetResult(bool success) {
345 // Setting ready status.
348 SignalPortComplete(this);
350 SignalPortError(this);
354 // TODO: merge this with SendTo above.
355 void UDPPort::OnSendPacket(const void* data, size_t size, StunRequest* req) {
356 StunBindingRequest* sreq = static_cast<StunBindingRequest*>(req);
357 talk_base::PacketOptions options(DefaultDscpValue());
358 if (socket_->SendTo(data, size, sreq->server_addr(), options) < 0)
359 PLOG(LERROR, socket_->GetError()) << "sendto";
362 } // namespace cricket