Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / libjingle / source / talk / p2p / base / turnport.cc
1 /*
2  * libjingle
3  * Copyright 2012, 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 #include "talk/p2p/base/turnport.h"
29
30 #include <functional>
31
32 #include "talk/base/asyncpacketsocket.h"
33 #include "talk/base/byteorder.h"
34 #include "talk/base/common.h"
35 #include "talk/base/logging.h"
36 #include "talk/base/nethelpers.h"
37 #include "talk/base/socketaddress.h"
38 #include "talk/base/stringencode.h"
39 #include "talk/p2p/base/common.h"
40 #include "talk/p2p/base/stun.h"
41
42 namespace cricket {
43
44 // TODO(juberti): Move to stun.h when relay messages have been renamed.
45 static const int TURN_ALLOCATE_REQUEST = STUN_ALLOCATE_REQUEST;
46
47 // TODO(juberti): Extract to turnmessage.h
48 static const int TURN_DEFAULT_PORT = 3478;
49 static const int TURN_CHANNEL_NUMBER_START = 0x4000;
50 static const int TURN_PERMISSION_TIMEOUT = 5 * 60 * 1000;  // 5 minutes
51
52 static const size_t TURN_CHANNEL_HEADER_SIZE = 4U;
53
54 inline bool IsTurnChannelData(uint16 msg_type) {
55   return ((msg_type & 0xC000) == 0x4000);  // MSB are 0b01
56 }
57
58 static int GetRelayPreference(cricket::ProtocolType proto, bool secure) {
59   int relay_preference = ICE_TYPE_PREFERENCE_RELAY;
60   if (proto == cricket::PROTO_TCP) {
61     relay_preference -= 1;
62     if (secure)
63       relay_preference -= 1;
64   }
65
66   ASSERT(relay_preference >= 0);
67   return relay_preference;
68 }
69
70 class TurnAllocateRequest : public StunRequest {
71  public:
72   explicit TurnAllocateRequest(TurnPort* port);
73   virtual void Prepare(StunMessage* request);
74   virtual void OnResponse(StunMessage* response);
75   virtual void OnErrorResponse(StunMessage* response);
76   virtual void OnTimeout();
77
78  private:
79   // Handles authentication challenge from the server.
80   void OnAuthChallenge(StunMessage* response, int code);
81   void OnUnknownAttribute(StunMessage* response);
82
83   TurnPort* port_;
84 };
85
86 class TurnRefreshRequest : public StunRequest {
87  public:
88   explicit TurnRefreshRequest(TurnPort* port);
89   virtual void Prepare(StunMessage* request);
90   virtual void OnResponse(StunMessage* response);
91   virtual void OnErrorResponse(StunMessage* response);
92   virtual void OnTimeout();
93
94  private:
95   TurnPort* port_;
96 };
97
98 class TurnCreatePermissionRequest : public StunRequest,
99                                     public sigslot::has_slots<> {
100  public:
101   TurnCreatePermissionRequest(TurnPort* port, TurnEntry* entry,
102                               const talk_base::SocketAddress& ext_addr);
103   virtual void Prepare(StunMessage* request);
104   virtual void OnResponse(StunMessage* response);
105   virtual void OnErrorResponse(StunMessage* response);
106   virtual void OnTimeout();
107
108  private:
109   void OnEntryDestroyed(TurnEntry* entry);
110
111   TurnPort* port_;
112   TurnEntry* entry_;
113   talk_base::SocketAddress ext_addr_;
114 };
115
116 class TurnChannelBindRequest : public StunRequest,
117                                public sigslot::has_slots<> {
118  public:
119   TurnChannelBindRequest(TurnPort* port, TurnEntry* entry, int channel_id,
120                          const talk_base::SocketAddress& ext_addr);
121   virtual void Prepare(StunMessage* request);
122   virtual void OnResponse(StunMessage* response);
123   virtual void OnErrorResponse(StunMessage* response);
124   virtual void OnTimeout();
125
126  private:
127   void OnEntryDestroyed(TurnEntry* entry);
128
129   TurnPort* port_;
130   TurnEntry* entry_;
131   int channel_id_;
132   talk_base::SocketAddress ext_addr_;
133 };
134
135 // Manages a "connection" to a remote destination. We will attempt to bring up
136 // a channel for this remote destination to reduce the overhead of sending data.
137 class TurnEntry : public sigslot::has_slots<> {
138  public:
139   enum BindState { STATE_UNBOUND, STATE_BINDING, STATE_BOUND };
140   TurnEntry(TurnPort* port, int channel_id,
141             const talk_base::SocketAddress& ext_addr);
142
143   TurnPort* port() { return port_; }
144
145   int channel_id() const { return channel_id_; }
146   const talk_base::SocketAddress& address() const { return ext_addr_; }
147   BindState state() const { return state_; }
148
149   // Helper methods to send permission and channel bind requests.
150   void SendCreatePermissionRequest();
151   void SendChannelBindRequest(int delay);
152   // Sends a packet to the given destination address.
153   // This will wrap the packet in STUN if necessary.
154   int Send(const void* data, size_t size, bool payload,
155            const talk_base::PacketOptions& options);
156
157   void OnCreatePermissionSuccess();
158   void OnCreatePermissionError(StunMessage* response, int code);
159   void OnChannelBindSuccess();
160   void OnChannelBindError(StunMessage* response, int code);
161   // Signal sent when TurnEntry is destroyed.
162   sigslot::signal1<TurnEntry*> SignalDestroyed;
163
164  private:
165   TurnPort* port_;
166   int channel_id_;
167   talk_base::SocketAddress ext_addr_;
168   BindState state_;
169 };
170
171 TurnPort::TurnPort(talk_base::Thread* thread,
172                    talk_base::PacketSocketFactory* factory,
173                    talk_base::Network* network,
174                    talk_base::AsyncPacketSocket* socket,
175                    const std::string& username,
176                    const std::string& password,
177                    const ProtocolAddress& server_address,
178                    const RelayCredentials& credentials)
179     : Port(thread, factory, network, socket->GetLocalAddress().ipaddr(),
180            username, password),
181       server_address_(server_address),
182       credentials_(credentials),
183       socket_(socket),
184       resolver_(NULL),
185       error_(0),
186       request_manager_(thread),
187       next_channel_number_(TURN_CHANNEL_NUMBER_START),
188       connected_(false) {
189   request_manager_.SignalSendPacket.connect(this, &TurnPort::OnSendStunPacket);
190 }
191
192 TurnPort::TurnPort(talk_base::Thread* thread,
193                    talk_base::PacketSocketFactory* factory,
194                    talk_base::Network* network,
195                    const talk_base::IPAddress& ip,
196                    int min_port, int max_port,
197                    const std::string& username,
198                    const std::string& password,
199                    const ProtocolAddress& server_address,
200                    const RelayCredentials& credentials)
201     : Port(thread, RELAY_PORT_TYPE, factory, network, ip, min_port, max_port,
202            username, password),
203       server_address_(server_address),
204       credentials_(credentials),
205       socket_(NULL),
206       resolver_(NULL),
207       error_(0),
208       request_manager_(thread),
209       next_channel_number_(TURN_CHANNEL_NUMBER_START),
210       connected_(false) {
211   request_manager_.SignalSendPacket.connect(this, &TurnPort::OnSendStunPacket);
212 }
213
214 TurnPort::~TurnPort() {
215   // TODO(juberti): Should this even be necessary?
216   while (!entries_.empty()) {
217     DestroyEntry(entries_.front()->address());
218   }
219   if (resolver_) {
220     resolver_->Destroy(false);
221   }
222   if (!SharedSocket()) {
223     delete socket_;
224   }
225 }
226
227 void TurnPort::PrepareAddress() {
228   if (credentials_.username.empty() ||
229       credentials_.password.empty()) {
230     LOG(LS_ERROR) << "Allocation can't be started without setting the"
231                   << " TURN server credentials for the user.";
232     OnAllocateError();
233     return;
234   }
235
236   if (!server_address_.address.port()) {
237     // We will set default TURN port, if no port is set in the address.
238     server_address_.address.SetPort(TURN_DEFAULT_PORT);
239   }
240
241   if (server_address_.address.IsUnresolved()) {
242     ResolveTurnAddress(server_address_.address);
243   } else {
244     // If protocol family of server address doesn't match with local, return.
245     if (!IsCompatibleAddress(server_address_.address)) {
246       LOG(LS_ERROR) << "Server IP address family does not match with "
247                     << "local host address family type";
248       OnAllocateError();
249       return;
250     }
251
252     LOG_J(LS_INFO, this) << "Trying to connect to TURN server via "
253                          << ProtoToString(server_address_.proto) << " @ "
254                          << server_address_.address.ToSensitiveString();
255     if (server_address_.proto == PROTO_UDP && !SharedSocket()) {
256       socket_ = socket_factory()->CreateUdpSocket(
257           talk_base::SocketAddress(ip(), 0), min_port(), max_port());
258     } else if (server_address_.proto == PROTO_TCP) {
259       ASSERT(!SharedSocket());
260       int opts = talk_base::PacketSocketFactory::OPT_STUN;
261       // If secure bit is enabled in server address, use TLS over TCP.
262       if (server_address_.secure) {
263         opts |= talk_base::PacketSocketFactory::OPT_TLS;
264       }
265       socket_ = socket_factory()->CreateClientTcpSocket(
266           talk_base::SocketAddress(ip(), 0), server_address_.address,
267           proxy(), user_agent(), opts);
268     }
269
270     if (!socket_) {
271       OnAllocateError();
272       return;
273     }
274
275     // Apply options if any.
276     for (SocketOptionsMap::iterator iter = socket_options_.begin();
277          iter != socket_options_.end(); ++iter) {
278       socket_->SetOption(iter->first, iter->second);
279     }
280
281     if (!SharedSocket()) {
282       // If socket is shared, AllocationSequence will receive the packet.
283       socket_->SignalReadPacket.connect(this, &TurnPort::OnReadPacket);
284     }
285
286     socket_->SignalReadyToSend.connect(this, &TurnPort::OnReadyToSend);
287
288     if (server_address_.proto == PROTO_TCP) {
289       socket_->SignalConnect.connect(this, &TurnPort::OnSocketConnect);
290       socket_->SignalClose.connect(this, &TurnPort::OnSocketClose);
291     } else {
292       // If its UDP, send AllocateRequest now.
293       // For TCP and TLS AllcateRequest will be sent by OnSocketConnect.
294       SendRequest(new TurnAllocateRequest(this), 0);
295     }
296   }
297 }
298
299 void TurnPort::OnSocketConnect(talk_base::AsyncPacketSocket* socket) {
300   ASSERT(server_address_.proto == PROTO_TCP);
301   // Do not use this port if the socket bound to a different address than
302   // the one we asked for. This is seen in Chrome, where TCP sockets cannot be
303   // given a binding address, and the platform is expected to pick the
304   // correct local address.
305   if (socket->GetLocalAddress().ipaddr() != ip()) {
306     LOG(LS_WARNING) << "Socket is bound to a different address then the "
307                     << "local port. Discarding TURN port.";
308     OnAllocateError();
309     return;
310   }
311
312   LOG(LS_INFO) << "TurnPort connected to " << socket->GetRemoteAddress()
313                << " using tcp.";
314   SendRequest(new TurnAllocateRequest(this), 0);
315 }
316
317 void TurnPort::OnSocketClose(talk_base::AsyncPacketSocket* socket, int error) {
318   LOG_J(LS_WARNING, this) << "Connection with server failed, error=" << error;
319   if (!connected_) {
320     OnAllocateError();
321   }
322 }
323
324 Connection* TurnPort::CreateConnection(const Candidate& address,
325                                        CandidateOrigin origin) {
326   // TURN-UDP can only connect to UDP candidates.
327   if (address.protocol() != UDP_PROTOCOL_NAME) {
328     return NULL;
329   }
330
331   if (!IsCompatibleAddress(address.address())) {
332     return NULL;
333   }
334
335   // Create an entry, if needed, so we can get our permissions set up correctly.
336   CreateEntry(address.address());
337
338   // A TURN port will have two candiates, STUN and TURN. STUN may not
339   // present in all cases. If present stun candidate will be added first
340   // and TURN candidate later.
341   for (size_t index = 0; index < Candidates().size(); ++index) {
342     if (Candidates()[index].type() == RELAY_PORT_TYPE) {
343       ProxyConnection* conn = new ProxyConnection(this, index, address);
344       conn->SignalDestroyed.connect(this, &TurnPort::OnConnectionDestroyed);
345       AddConnection(conn);
346       return conn;
347     }
348   }
349   return NULL;
350 }
351
352 int TurnPort::SetOption(talk_base::Socket::Option opt, int value) {
353   if (!socket_) {
354     // If socket is not created yet, these options will be applied during socket
355     // creation.
356     socket_options_[opt] = value;
357     return 0;
358   }
359   return socket_->SetOption(opt, value);
360 }
361
362 int TurnPort::GetOption(talk_base::Socket::Option opt, int* value) {
363   if (!socket_) {
364     SocketOptionsMap::const_iterator it = socket_options_.find(opt);
365     if (it == socket_options_.end()) {
366       return -1;
367     }
368     *value = it->second;
369     return 0;
370   }
371
372   return socket_->GetOption(opt, value);
373 }
374
375 int TurnPort::GetError() {
376   return error_;
377 }
378
379 int TurnPort::SendTo(const void* data, size_t size,
380                      const talk_base::SocketAddress& addr,
381                      const talk_base::PacketOptions& options,
382                      bool payload) {
383   // Try to find an entry for this specific address; we should have one.
384   TurnEntry* entry = FindEntry(addr);
385   ASSERT(entry != NULL);
386   if (!entry) {
387     return 0;
388   }
389
390   if (!connected()) {
391     error_ = EWOULDBLOCK;
392     return SOCKET_ERROR;
393   }
394
395   // Send the actual contents to the server using the usual mechanism.
396   int sent = entry->Send(data, size, payload, options);
397   if (sent <= 0) {
398     return SOCKET_ERROR;
399   }
400
401   // The caller of the function is expecting the number of user data bytes,
402   // rather than the size of the packet.
403   return static_cast<int>(size);
404 }
405
406 void TurnPort::OnReadPacket(
407     talk_base::AsyncPacketSocket* socket, const char* data, size_t size,
408     const talk_base::SocketAddress& remote_addr,
409     const talk_base::PacketTime& packet_time) {
410   ASSERT(socket == socket_);
411   ASSERT(remote_addr == server_address_.address);
412
413   // The message must be at least the size of a channel header.
414   if (size < TURN_CHANNEL_HEADER_SIZE) {
415     LOG_J(LS_WARNING, this) << "Received TURN message that was too short";
416     return;
417   }
418
419   // Check the message type, to see if is a Channel Data message.
420   // The message will either be channel data, a TURN data indication, or
421   // a response to a previous request.
422   uint16 msg_type = talk_base::GetBE16(data);
423   if (IsTurnChannelData(msg_type)) {
424     HandleChannelData(msg_type, data, size, packet_time);
425   } else if (msg_type == TURN_DATA_INDICATION) {
426     HandleDataIndication(data, size, packet_time);
427   } else {
428     // This must be a response for one of our requests.
429     // Check success responses, but not errors, for MESSAGE-INTEGRITY.
430     if (IsStunSuccessResponseType(msg_type) &&
431         !StunMessage::ValidateMessageIntegrity(data, size, hash())) {
432       LOG_J(LS_WARNING, this) << "Received TURN message with invalid "
433                               << "message integrity, msg_type=" << msg_type;
434       return;
435     }
436     request_manager_.CheckResponse(data, size);
437   }
438 }
439
440 void TurnPort::OnReadyToSend(talk_base::AsyncPacketSocket* socket) {
441   if (connected_) {
442     Port::OnReadyToSend();
443   }
444 }
445
446 void TurnPort::ResolveTurnAddress(const talk_base::SocketAddress& address) {
447   if (resolver_)
448     return;
449
450   resolver_ = socket_factory()->CreateAsyncResolver();
451   resolver_->SignalDone.connect(this, &TurnPort::OnResolveResult);
452   resolver_->Start(address);
453 }
454
455 void TurnPort::OnResolveResult(talk_base::AsyncResolverInterface* resolver) {
456   ASSERT(resolver == resolver_);
457   talk_base::SocketAddress resolved_address;
458   if (resolver_->GetError() != 0 ||
459       !resolver_->GetResolvedAddress(ip().family(), &resolved_address)) {
460     LOG_J(LS_WARNING, this) << "TURN host lookup received error "
461                             << resolver_->GetError();
462     OnAllocateError();
463     return;
464   }
465   // Signal needs both resolved and unresolved address. After signal is sent
466   // we can copy resolved address back into |server_address_|.
467   SignalResolvedServerAddress(this, server_address_.address,
468                               resolved_address);
469   server_address_.address = resolved_address;
470   PrepareAddress();
471 }
472
473 void TurnPort::OnSendStunPacket(const void* data, size_t size,
474                                 StunRequest* request) {
475   talk_base::PacketOptions options(DefaultDscpValue());
476   if (Send(data, size, options) < 0) {
477     LOG_J(LS_ERROR, this) << "Failed to send TURN message, err="
478                           << socket_->GetError();
479   }
480 }
481
482 void TurnPort::OnStunAddress(const talk_base::SocketAddress& address) {
483   if (server_address_.proto == PROTO_UDP  &&
484       address != socket_->GetLocalAddress()) {
485     AddAddress(address,  // Candidate address.
486                socket_->GetLocalAddress(),  // Base address.
487                socket_->GetLocalAddress(),  // Related address.
488                UDP_PROTOCOL_NAME,
489                STUN_PORT_TYPE,
490                ICE_TYPE_PREFERENCE_SRFLX,
491                false);
492   }
493 }
494
495 void TurnPort::OnAllocateSuccess(const talk_base::SocketAddress& address,
496                                  const talk_base::SocketAddress& stun_address) {
497   // For relayed candidate, Base is the candidate itself.
498   connected_ = true;
499   AddAddress(address,  // Candidate address.
500              address,  // Base address.
501              stun_address,  // Related address.
502              UDP_PROTOCOL_NAME,
503              RELAY_PORT_TYPE,
504              GetRelayPreference(server_address_.proto, server_address_.secure),
505              true);
506 }
507
508 void TurnPort::OnAllocateError() {
509   // We will send SignalPortError asynchronously as this can be sent during
510   // port initialization. This way it will not be blocking other port
511   // creation.
512   thread()->Post(this, MSG_ERROR);
513 }
514
515 void TurnPort::OnMessage(talk_base::Message* message) {
516   if (message->message_id == MSG_ERROR) {
517     SignalPortError(this);
518     return;
519   }
520
521   Port::OnMessage(message);
522 }
523
524 void TurnPort::OnAllocateRequestTimeout() {
525   OnAllocateError();
526 }
527
528 void TurnPort::HandleDataIndication(const char* data, size_t size,
529                                     const talk_base::PacketTime& packet_time) {
530   // Read in the message, and process according to RFC5766, Section 10.4.
531   talk_base::ByteBuffer buf(data, size);
532   TurnMessage msg;
533   if (!msg.Read(&buf)) {
534     LOG_J(LS_WARNING, this) << "Received invalid TURN data indication";
535     return;
536   }
537
538   // Check mandatory attributes.
539   const StunAddressAttribute* addr_attr =
540       msg.GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
541   if (!addr_attr) {
542     LOG_J(LS_WARNING, this) << "Missing STUN_ATTR_XOR_PEER_ADDRESS attribute "
543                             << "in data indication.";
544     return;
545   }
546
547   const StunByteStringAttribute* data_attr =
548       msg.GetByteString(STUN_ATTR_DATA);
549   if (!data_attr) {
550     LOG_J(LS_WARNING, this) << "Missing STUN_ATTR_DATA attribute in "
551                             << "data indication.";
552     return;
553   }
554
555   // Verify that the data came from somewhere we think we have a permission for.
556   talk_base::SocketAddress ext_addr(addr_attr->GetAddress());
557   if (!HasPermission(ext_addr.ipaddr())) {
558     LOG_J(LS_WARNING, this) << "Received TURN data indication with invalid "
559                             << "peer address, addr="
560                             << ext_addr.ToSensitiveString();
561     return;
562   }
563
564   DispatchPacket(data_attr->bytes(), data_attr->length(), ext_addr,
565                  PROTO_UDP, packet_time);
566 }
567
568 void TurnPort::HandleChannelData(int channel_id, const char* data,
569                                  size_t size,
570                                  const talk_base::PacketTime& packet_time) {
571   // Read the message, and process according to RFC5766, Section 11.6.
572   //    0                   1                   2                   3
573   //    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
574   //   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
575   //   |         Channel Number        |            Length             |
576   //   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
577   //   |                                                               |
578   //   /                       Application Data                        /
579   //   /                                                               /
580   //   |                                                               |
581   //   |                               +-------------------------------+
582   //   |                               |
583   //   +-------------------------------+
584
585   // Extract header fields from the message.
586   uint16 len = talk_base::GetBE16(data + 2);
587   if (len > size - TURN_CHANNEL_HEADER_SIZE) {
588     LOG_J(LS_WARNING, this) << "Received TURN channel data message with "
589                             << "incorrect length, len=" << len;
590     return;
591   }
592   // Allowing messages larger than |len|, as ChannelData can be padded.
593
594   TurnEntry* entry = FindEntry(channel_id);
595   if (!entry) {
596     LOG_J(LS_WARNING, this) << "Received TURN channel data message for invalid "
597                             << "channel, channel_id=" << channel_id;
598     return;
599   }
600
601   DispatchPacket(data + TURN_CHANNEL_HEADER_SIZE, len, entry->address(),
602                  PROTO_UDP, packet_time);
603 }
604
605 void TurnPort::DispatchPacket(const char* data, size_t size,
606     const talk_base::SocketAddress& remote_addr,
607     ProtocolType proto, const talk_base::PacketTime& packet_time) {
608   if (Connection* conn = GetConnection(remote_addr)) {
609     conn->OnReadPacket(data, size, packet_time);
610   } else {
611     Port::OnReadPacket(data, size, remote_addr, proto);
612   }
613 }
614
615 bool TurnPort::ScheduleRefresh(int lifetime) {
616   // Lifetime is in seconds; we schedule a refresh for one minute less.
617   if (lifetime < 2 * 60) {
618     LOG_J(LS_WARNING, this) << "Received response with lifetime that was "
619                             << "too short, lifetime=" << lifetime;
620     return false;
621   }
622
623   SendRequest(new TurnRefreshRequest(this), (lifetime - 60) * 1000);
624   return true;
625 }
626
627 void TurnPort::SendRequest(StunRequest* req, int delay) {
628   request_manager_.SendDelayed(req, delay);
629 }
630
631 void TurnPort::AddRequestAuthInfo(StunMessage* msg) {
632   // If we've gotten the necessary data from the server, add it to our request.
633   VERIFY(!hash_.empty());
634   VERIFY(msg->AddAttribute(new StunByteStringAttribute(
635       STUN_ATTR_USERNAME, credentials_.username)));
636   VERIFY(msg->AddAttribute(new StunByteStringAttribute(
637       STUN_ATTR_REALM, realm_)));
638   VERIFY(msg->AddAttribute(new StunByteStringAttribute(
639       STUN_ATTR_NONCE, nonce_)));
640   VERIFY(msg->AddMessageIntegrity(hash()));
641 }
642
643 int TurnPort::Send(const void* data, size_t len,
644                    const talk_base::PacketOptions& options) {
645   return socket_->SendTo(data, len, server_address_.address, options);
646 }
647
648 void TurnPort::UpdateHash() {
649   VERIFY(ComputeStunCredentialHash(credentials_.username, realm_,
650                                    credentials_.password, &hash_));
651 }
652
653 bool TurnPort::UpdateNonce(StunMessage* response) {
654   // When stale nonce error received, we should update
655   // hash and store realm and nonce.
656   // Check the mandatory attributes.
657   const StunByteStringAttribute* realm_attr =
658       response->GetByteString(STUN_ATTR_REALM);
659   if (!realm_attr) {
660     LOG(LS_ERROR) << "Missing STUN_ATTR_REALM attribute in "
661                   << "stale nonce error response.";
662     return false;
663   }
664   set_realm(realm_attr->GetString());
665
666   const StunByteStringAttribute* nonce_attr =
667       response->GetByteString(STUN_ATTR_NONCE);
668   if (!nonce_attr) {
669     LOG(LS_ERROR) << "Missing STUN_ATTR_NONCE attribute in "
670                   << "stale nonce error response.";
671     return false;
672   }
673   set_nonce(nonce_attr->GetString());
674   return true;
675 }
676
677 static bool MatchesIP(TurnEntry* e, talk_base::IPAddress ipaddr) {
678   return e->address().ipaddr() == ipaddr;
679 }
680 bool TurnPort::HasPermission(const talk_base::IPAddress& ipaddr) const {
681   return (std::find_if(entries_.begin(), entries_.end(),
682       std::bind2nd(std::ptr_fun(MatchesIP), ipaddr)) != entries_.end());
683 }
684
685 static bool MatchesAddress(TurnEntry* e, talk_base::SocketAddress addr) {
686   return e->address() == addr;
687 }
688 TurnEntry* TurnPort::FindEntry(const talk_base::SocketAddress& addr) const {
689   EntryList::const_iterator it = std::find_if(entries_.begin(), entries_.end(),
690       std::bind2nd(std::ptr_fun(MatchesAddress), addr));
691   return (it != entries_.end()) ? *it : NULL;
692 }
693
694 static bool MatchesChannelId(TurnEntry* e, int id) {
695   return e->channel_id() == id;
696 }
697 TurnEntry* TurnPort::FindEntry(int channel_id) const {
698   EntryList::const_iterator it = std::find_if(entries_.begin(), entries_.end(),
699       std::bind2nd(std::ptr_fun(MatchesChannelId), channel_id));
700   return (it != entries_.end()) ? *it : NULL;
701 }
702
703 TurnEntry* TurnPort::CreateEntry(const talk_base::SocketAddress& addr) {
704   ASSERT(FindEntry(addr) == NULL);
705   TurnEntry* entry = new TurnEntry(this, next_channel_number_++, addr);
706   entries_.push_back(entry);
707   return entry;
708 }
709
710 void TurnPort::DestroyEntry(const talk_base::SocketAddress& addr) {
711   TurnEntry* entry = FindEntry(addr);
712   ASSERT(entry != NULL);
713   entry->SignalDestroyed(entry);
714   entries_.remove(entry);
715   delete entry;
716 }
717
718 void TurnPort::OnConnectionDestroyed(Connection* conn) {
719   // Destroying TurnEntry for the connection, which is already destroyed.
720   DestroyEntry(conn->remote_candidate().address());
721 }
722
723 TurnAllocateRequest::TurnAllocateRequest(TurnPort* port)
724     : StunRequest(new TurnMessage()),
725       port_(port) {
726 }
727
728 void TurnAllocateRequest::Prepare(StunMessage* request) {
729   // Create the request as indicated in RFC 5766, Section 6.1.
730   request->SetType(TURN_ALLOCATE_REQUEST);
731   StunUInt32Attribute* transport_attr = StunAttribute::CreateUInt32(
732       STUN_ATTR_REQUESTED_TRANSPORT);
733   transport_attr->SetValue(IPPROTO_UDP << 24);
734   VERIFY(request->AddAttribute(transport_attr));
735   if (!port_->hash().empty()) {
736     port_->AddRequestAuthInfo(request);
737   }
738 }
739
740 void TurnAllocateRequest::OnResponse(StunMessage* response) {
741   // Check mandatory attributes as indicated in RFC5766, Section 6.3.
742   const StunAddressAttribute* mapped_attr =
743       response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
744   if (!mapped_attr) {
745     LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_XOR_MAPPED_ADDRESS "
746                              << "attribute in allocate success response";
747     return;
748   }
749
750   // Using XOR-Mapped-Address for stun.
751   port_->OnStunAddress(mapped_attr->GetAddress());
752
753   const StunAddressAttribute* relayed_attr =
754       response->GetAddress(STUN_ATTR_XOR_RELAYED_ADDRESS);
755   if (!relayed_attr) {
756     LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_XOR_RELAYED_ADDRESS "
757                              << "attribute in allocate success response";
758     return;
759   }
760
761   const StunUInt32Attribute* lifetime_attr =
762       response->GetUInt32(STUN_ATTR_TURN_LIFETIME);
763   if (!lifetime_attr) {
764     LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_TURN_LIFETIME attribute in "
765                              << "allocate success response";
766     return;
767   }
768   // Notify the port the allocate succeeded, and schedule a refresh request.
769   port_->OnAllocateSuccess(relayed_attr->GetAddress(),
770                            mapped_attr->GetAddress());
771   port_->ScheduleRefresh(lifetime_attr->value());
772 }
773
774 void TurnAllocateRequest::OnErrorResponse(StunMessage* response) {
775   // Process error response according to RFC5766, Section 6.4.
776   const StunErrorCodeAttribute* error_code = response->GetErrorCode();
777   switch (error_code->code()) {
778     case STUN_ERROR_UNAUTHORIZED:       // Unauthrorized.
779       OnAuthChallenge(response, error_code->code());
780       break;
781     default:
782       LOG_J(LS_WARNING, port_) << "Allocate response error, code="
783                                << error_code->code();
784       port_->OnAllocateError();
785   }
786 }
787
788 void TurnAllocateRequest::OnTimeout() {
789   LOG_J(LS_WARNING, port_) << "Allocate request timeout";
790   port_->OnAllocateRequestTimeout();
791 }
792
793 void TurnAllocateRequest::OnAuthChallenge(StunMessage* response, int code) {
794   // If we failed to authenticate even after we sent our credentials, fail hard.
795   if (code == STUN_ERROR_UNAUTHORIZED && !port_->hash().empty()) {
796     LOG_J(LS_WARNING, port_) << "Failed to authenticate with the server "
797                              << "after challenge.";
798     port_->OnAllocateError();
799     return;
800   }
801
802   // Check the mandatory attributes.
803   const StunByteStringAttribute* realm_attr =
804       response->GetByteString(STUN_ATTR_REALM);
805   if (!realm_attr) {
806     LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_REALM attribute in "
807                              << "allocate unauthorized response.";
808     return;
809   }
810   port_->set_realm(realm_attr->GetString());
811
812   const StunByteStringAttribute* nonce_attr =
813       response->GetByteString(STUN_ATTR_NONCE);
814   if (!nonce_attr) {
815     LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_NONCE attribute in "
816                              << "allocate unauthorized response.";
817     return;
818   }
819   port_->set_nonce(nonce_attr->GetString());
820
821   // Send another allocate request, with the received realm and nonce values.
822   port_->SendRequest(new TurnAllocateRequest(port_), 0);
823 }
824
825 TurnRefreshRequest::TurnRefreshRequest(TurnPort* port)
826     : StunRequest(new TurnMessage()),
827       port_(port) {
828 }
829
830 void TurnRefreshRequest::Prepare(StunMessage* request) {
831   // Create the request as indicated in RFC 5766, Section 7.1.
832   // No attributes need to be included.
833   request->SetType(TURN_REFRESH_REQUEST);
834   port_->AddRequestAuthInfo(request);
835 }
836
837 void TurnRefreshRequest::OnResponse(StunMessage* response) {
838   // Check mandatory attributes as indicated in RFC5766, Section 7.3.
839   const StunUInt32Attribute* lifetime_attr =
840       response->GetUInt32(STUN_ATTR_TURN_LIFETIME);
841   if (!lifetime_attr) {
842     LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_TURN_LIFETIME attribute in "
843                              << "refresh success response.";
844     return;
845   }
846
847   // Schedule a refresh based on the returned lifetime value.
848   port_->ScheduleRefresh(lifetime_attr->value());
849 }
850
851 void TurnRefreshRequest::OnErrorResponse(StunMessage* response) {
852   // TODO(juberti): Handle 437 error response as a success.
853   const StunErrorCodeAttribute* error_code = response->GetErrorCode();
854   LOG_J(LS_WARNING, port_) << "Refresh response error, code="
855                            << error_code->code();
856
857   if (error_code->code() == STUN_ERROR_STALE_NONCE) {
858     if (port_->UpdateNonce(response)) {
859       // Send RefreshRequest immediately.
860       port_->SendRequest(new TurnRefreshRequest(port_), 0);
861     }
862   }
863 }
864
865 void TurnRefreshRequest::OnTimeout() {
866 }
867
868 TurnCreatePermissionRequest::TurnCreatePermissionRequest(
869     TurnPort* port, TurnEntry* entry,
870     const talk_base::SocketAddress& ext_addr)
871     : StunRequest(new TurnMessage()),
872       port_(port),
873       entry_(entry),
874       ext_addr_(ext_addr) {
875   entry_->SignalDestroyed.connect(
876       this, &TurnCreatePermissionRequest::OnEntryDestroyed);
877 }
878
879 void TurnCreatePermissionRequest::Prepare(StunMessage* request) {
880   // Create the request as indicated in RFC5766, Section 9.1.
881   request->SetType(TURN_CREATE_PERMISSION_REQUEST);
882   VERIFY(request->AddAttribute(new StunXorAddressAttribute(
883       STUN_ATTR_XOR_PEER_ADDRESS, ext_addr_)));
884   port_->AddRequestAuthInfo(request);
885 }
886
887 void TurnCreatePermissionRequest::OnResponse(StunMessage* response) {
888   if (entry_) {
889     entry_->OnCreatePermissionSuccess();
890   }
891 }
892
893 void TurnCreatePermissionRequest::OnErrorResponse(StunMessage* response) {
894   if (entry_) {
895     const StunErrorCodeAttribute* error_code = response->GetErrorCode();
896     entry_->OnCreatePermissionError(response, error_code->code());
897   }
898 }
899
900 void TurnCreatePermissionRequest::OnTimeout() {
901   LOG_J(LS_WARNING, port_) << "Create permission timeout";
902 }
903
904 void TurnCreatePermissionRequest::OnEntryDestroyed(TurnEntry* entry) {
905   ASSERT(entry_ == entry);
906   entry_ = NULL;
907 }
908
909 TurnChannelBindRequest::TurnChannelBindRequest(
910     TurnPort* port, TurnEntry* entry,
911     int channel_id, const talk_base::SocketAddress& ext_addr)
912     : StunRequest(new TurnMessage()),
913       port_(port),
914       entry_(entry),
915       channel_id_(channel_id),
916       ext_addr_(ext_addr) {
917   entry_->SignalDestroyed.connect(
918       this, &TurnChannelBindRequest::OnEntryDestroyed);
919 }
920
921 void TurnChannelBindRequest::Prepare(StunMessage* request) {
922   // Create the request as indicated in RFC5766, Section 11.1.
923   request->SetType(TURN_CHANNEL_BIND_REQUEST);
924   VERIFY(request->AddAttribute(new StunUInt32Attribute(
925       STUN_ATTR_CHANNEL_NUMBER, channel_id_ << 16)));
926   VERIFY(request->AddAttribute(new StunXorAddressAttribute(
927       STUN_ATTR_XOR_PEER_ADDRESS, ext_addr_)));
928   port_->AddRequestAuthInfo(request);
929 }
930
931 void TurnChannelBindRequest::OnResponse(StunMessage* response) {
932   if (entry_) {
933     entry_->OnChannelBindSuccess();
934     // Refresh the channel binding just under the permission timeout
935     // threshold. The channel binding has a longer lifetime, but
936     // this is the easiest way to keep both the channel and the
937     // permission from expiring.
938     entry_->SendChannelBindRequest(TURN_PERMISSION_TIMEOUT - 60 * 1000);
939   }
940 }
941
942 void TurnChannelBindRequest::OnErrorResponse(StunMessage* response) {
943   if (entry_) {
944     const StunErrorCodeAttribute* error_code = response->GetErrorCode();
945     entry_->OnChannelBindError(response, error_code->code());
946   }
947 }
948
949 void TurnChannelBindRequest::OnTimeout() {
950   LOG_J(LS_WARNING, port_) << "Channel bind timeout";
951 }
952
953 void TurnChannelBindRequest::OnEntryDestroyed(TurnEntry* entry) {
954   ASSERT(entry_ == entry);
955   entry_ = NULL;
956 }
957
958 TurnEntry::TurnEntry(TurnPort* port, int channel_id,
959                      const talk_base::SocketAddress& ext_addr)
960     : port_(port),
961       channel_id_(channel_id),
962       ext_addr_(ext_addr),
963       state_(STATE_UNBOUND) {
964   // Creating permission for |ext_addr_|.
965   SendCreatePermissionRequest();
966 }
967
968 void TurnEntry::SendCreatePermissionRequest() {
969   port_->SendRequest(new TurnCreatePermissionRequest(
970       port_, this, ext_addr_), 0);
971 }
972
973 void TurnEntry::SendChannelBindRequest(int delay) {
974   port_->SendRequest(new TurnChannelBindRequest(
975       port_, this, channel_id_, ext_addr_), delay);
976 }
977
978 int TurnEntry::Send(const void* data, size_t size, bool payload,
979                     const talk_base::PacketOptions& options) {
980   talk_base::ByteBuffer buf;
981   if (state_ != STATE_BOUND) {
982     // If we haven't bound the channel yet, we have to use a Send Indication.
983     TurnMessage msg;
984     msg.SetType(TURN_SEND_INDICATION);
985     msg.SetTransactionID(
986         talk_base::CreateRandomString(kStunTransactionIdLength));
987     VERIFY(msg.AddAttribute(new StunXorAddressAttribute(
988         STUN_ATTR_XOR_PEER_ADDRESS, ext_addr_)));
989     VERIFY(msg.AddAttribute(new StunByteStringAttribute(
990         STUN_ATTR_DATA, data, size)));
991     VERIFY(msg.Write(&buf));
992
993     // If we're sending real data, request a channel bind that we can use later.
994     if (state_ == STATE_UNBOUND && payload) {
995       SendChannelBindRequest(0);
996       state_ = STATE_BINDING;
997     }
998   } else {
999     // If the channel is bound, we can send the data as a Channel Message.
1000     buf.WriteUInt16(channel_id_);
1001     buf.WriteUInt16(static_cast<uint16>(size));
1002     buf.WriteBytes(reinterpret_cast<const char*>(data), size);
1003   }
1004   return port_->Send(buf.Data(), buf.Length(), options);
1005 }
1006
1007 void TurnEntry::OnCreatePermissionSuccess() {
1008   LOG_J(LS_INFO, port_) << "Create permission for "
1009                         << ext_addr_.ToSensitiveString()
1010                         << " succeeded";
1011   // For success result code will be 0.
1012   port_->SignalCreatePermissionResult(port_, ext_addr_, 0);
1013 }
1014
1015 void TurnEntry::OnCreatePermissionError(StunMessage* response, int code) {
1016   LOG_J(LS_WARNING, port_) << "Create permission for "
1017                            << ext_addr_.ToSensitiveString()
1018                            << " failed, code=" << code;
1019   if (code == STUN_ERROR_STALE_NONCE) {
1020     if (port_->UpdateNonce(response)) {
1021       SendCreatePermissionRequest();
1022     }
1023   } else {
1024     // Send signal with error code.
1025     port_->SignalCreatePermissionResult(port_, ext_addr_, code);
1026   }
1027 }
1028
1029 void TurnEntry::OnChannelBindSuccess() {
1030   LOG_J(LS_INFO, port_) << "Channel bind for " << ext_addr_.ToSensitiveString()
1031                         << " succeeded";
1032   ASSERT(state_ == STATE_BINDING || state_ == STATE_BOUND);
1033   state_ = STATE_BOUND;
1034 }
1035
1036 void TurnEntry::OnChannelBindError(StunMessage* response, int code) {
1037   // TODO(mallinath) - Implement handling of error response for channel
1038   // bind request as per http://tools.ietf.org/html/rfc5766#section-11.3
1039   LOG_J(LS_WARNING, port_) << "Channel bind for "
1040                            << ext_addr_.ToSensitiveString()
1041                            << " failed, code=" << code;
1042   if (code == STUN_ERROR_STALE_NONCE) {
1043     if (port_->UpdateNonce(response)) {
1044       // Send channel bind request with fresh nonce.
1045       SendChannelBindRequest(0);
1046     }
1047   }
1048 }
1049
1050 }  // namespace cricket