1 /*
2  *  Copyright 2004 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "webrtc/p2p/client/basicportallocator.h"
12 
13 #include <algorithm>
14 #include <string>
15 #include <vector>
16 
17 #include "webrtc/api/umametrics.h"
18 #include "webrtc/p2p/base/basicpacketsocketfactory.h"
19 #include "webrtc/p2p/base/common.h"
20 #include "webrtc/p2p/base/port.h"
21 #include "webrtc/p2p/base/relayport.h"
22 #include "webrtc/p2p/base/stunport.h"
23 #include "webrtc/p2p/base/tcpport.h"
24 #include "webrtc/p2p/base/turnport.h"
25 #include "webrtc/p2p/base/udpport.h"
26 #include "webrtc/base/checks.h"
27 #include "webrtc/base/common.h"
28 #include "webrtc/base/helpers.h"
29 #include "webrtc/base/logging.h"
30 
31 using rtc::CreateRandomId;
32 
33 namespace {
34 
35 enum {
36   MSG_CONFIG_START,
37   MSG_CONFIG_READY,
38   MSG_ALLOCATE,
39   MSG_ALLOCATION_PHASE,
40   MSG_SEQUENCEOBJECTS_CREATED,
41   MSG_CONFIG_STOP,
42 };
43 
44 const int PHASE_UDP = 0;
45 const int PHASE_RELAY = 1;
46 const int PHASE_TCP = 2;
47 const int PHASE_SSLTCP = 3;
48 
49 const int kNumPhases = 4;
50 
51 // Gets protocol priority: UDP > TCP > SSLTCP.
GetProtocolPriority(cricket::ProtocolType protocol)52 int GetProtocolPriority(cricket::ProtocolType protocol) {
53   switch (protocol) {
54     case cricket::PROTO_UDP:
55       return 2;
56     case cricket::PROTO_TCP:
57       return 1;
58     case cricket::PROTO_SSLTCP:
59       return 0;
60     default:
61       RTC_NOTREACHED();
62       return 0;
63   }
64 }
65 // Gets address family priority:  IPv6 > IPv4 > Unspecified.
GetAddressFamilyPriority(int ip_family)66 int GetAddressFamilyPriority(int ip_family) {
67   switch (ip_family) {
68     case AF_INET6:
69       return 2;
70     case AF_INET:
71       return 1;
72     default:
73       RTC_NOTREACHED();
74       return 0;
75   }
76 }
77 
78 // Returns positive if a is better, negative if b is better, and 0 otherwise.
ComparePort(const cricket::Port * a,const cricket::Port * b)79 int ComparePort(const cricket::Port* a, const cricket::Port* b) {
80   int a_protocol = GetProtocolPriority(a->GetProtocol());
81   int b_protocol = GetProtocolPriority(b->GetProtocol());
82   int cmp_protocol = a_protocol - b_protocol;
83   if (cmp_protocol != 0) {
84     return cmp_protocol;
85   }
86 
87   int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
88   int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
89   return a_family - b_family;
90 }
91 
92 }  // namespace
93 
94 namespace cricket {
95 const uint32_t DISABLE_ALL_PHASES =
96     PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
97     PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
98 
99 // BasicPortAllocator
BasicPortAllocator(rtc::NetworkManager * network_manager,rtc::PacketSocketFactory * socket_factory)100 BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
101                                        rtc::PacketSocketFactory* socket_factory)
102     : network_manager_(network_manager), socket_factory_(socket_factory) {
103   RTC_DCHECK(network_manager_ != nullptr);
104   RTC_DCHECK(socket_factory_ != nullptr);
105   Construct();
106 }
107 
BasicPortAllocator(rtc::NetworkManager * network_manager)108 BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
109     : network_manager_(network_manager), socket_factory_(nullptr) {
110   RTC_DCHECK(network_manager_ != nullptr);
111   Construct();
112 }
113 
BasicPortAllocator(rtc::NetworkManager * network_manager,rtc::PacketSocketFactory * socket_factory,const ServerAddresses & stun_servers)114 BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
115                                        rtc::PacketSocketFactory* socket_factory,
116                                        const ServerAddresses& stun_servers)
117     : network_manager_(network_manager), socket_factory_(socket_factory) {
118   RTC_DCHECK(socket_factory_ != NULL);
119   SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false);
120   Construct();
121 }
122 
BasicPortAllocator(rtc::NetworkManager * network_manager,const ServerAddresses & stun_servers,const rtc::SocketAddress & relay_address_udp,const rtc::SocketAddress & relay_address_tcp,const rtc::SocketAddress & relay_address_ssl)123 BasicPortAllocator::BasicPortAllocator(
124     rtc::NetworkManager* network_manager,
125     const ServerAddresses& stun_servers,
126     const rtc::SocketAddress& relay_address_udp,
127     const rtc::SocketAddress& relay_address_tcp,
128     const rtc::SocketAddress& relay_address_ssl)
129     : network_manager_(network_manager), socket_factory_(NULL) {
130   std::vector<RelayServerConfig> turn_servers;
131   RelayServerConfig config(RELAY_GTURN);
132   if (!relay_address_udp.IsNil()) {
133     config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
134   }
135   if (!relay_address_tcp.IsNil()) {
136     config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
137   }
138   if (!relay_address_ssl.IsNil()) {
139     config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
140   }
141 
142   if (!config.ports.empty()) {
143     turn_servers.push_back(config);
144   }
145 
146   SetConfiguration(stun_servers, turn_servers, 0, false);
147   Construct();
148 }
149 
Construct()150 void BasicPortAllocator::Construct() {
151   allow_tcp_listen_ = true;
152 }
153 
OnIceRegathering(PortAllocatorSession * session,IceRegatheringReason reason)154 void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
155                                           IceRegatheringReason reason) {
156   if (!metrics_observer()) {
157     return;
158   }
159   // If the session has not been taken by an active channel, do not report the
160   // metric.
161   for (auto& allocator_session : pooled_sessions()) {
162     if (allocator_session.get() == session) {
163       return;
164     }
165   }
166 
167   metrics_observer()->IncrementEnumCounter(
168       webrtc::kEnumCounterIceRegathering, static_cast<int>(reason),
169       static_cast<int>(IceRegatheringReason::MAX_VALUE));
170 }
171 
~BasicPortAllocator()172 BasicPortAllocator::~BasicPortAllocator() {
173 }
174 
CreateSessionInternal(const std::string & content_name,int component,const std::string & ice_ufrag,const std::string & ice_pwd)175 PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
176     const std::string& content_name, int component,
177     const std::string& ice_ufrag, const std::string& ice_pwd) {
178   PortAllocatorSession* session = new BasicPortAllocatorSession(
179       this, content_name, component, ice_ufrag, ice_pwd);
180   session->SignalIceRegathering.connect(this,
181                                         &BasicPortAllocator::OnIceRegathering);
182   return session;
183 }
184 
AddTurnServer(const RelayServerConfig & turn_server)185 void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
186   std::vector<RelayServerConfig> new_turn_servers = turn_servers();
187   new_turn_servers.push_back(turn_server);
188   SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
189                    prune_turn_ports());
190 }
191 
192 // BasicPortAllocatorSession
BasicPortAllocatorSession(BasicPortAllocator * allocator,const std::string & content_name,int component,const std::string & ice_ufrag,const std::string & ice_pwd)193 BasicPortAllocatorSession::BasicPortAllocatorSession(
194     BasicPortAllocator* allocator,
195     const std::string& content_name,
196     int component,
197     const std::string& ice_ufrag,
198     const std::string& ice_pwd)
199     : PortAllocatorSession(content_name,
200                            component,
201                            ice_ufrag,
202                            ice_pwd,
203                            allocator->flags()),
204       allocator_(allocator),
205       network_thread_(NULL),
206       socket_factory_(allocator->socket_factory()),
207       allocation_started_(false),
208       network_manager_started_(false),
209       allocation_sequences_created_(false),
210       prune_turn_ports_(allocator->prune_turn_ports()) {
211   allocator_->network_manager()->SignalNetworksChanged.connect(
212       this, &BasicPortAllocatorSession::OnNetworksChanged);
213   allocator_->network_manager()->StartUpdating();
214 }
215 
~BasicPortAllocatorSession()216 BasicPortAllocatorSession::~BasicPortAllocatorSession() {
217   allocator_->network_manager()->StopUpdating();
218   if (network_thread_ != NULL)
219     network_thread_->Clear(this);
220 
221   for (uint32_t i = 0; i < sequences_.size(); ++i) {
222     // AllocationSequence should clear it's map entry for turn ports before
223     // ports are destroyed.
224     sequences_[i]->Clear();
225   }
226 
227   std::vector<PortData>::iterator it;
228   for (it = ports_.begin(); it != ports_.end(); it++)
229     delete it->port();
230 
231   for (uint32_t i = 0; i < configs_.size(); ++i)
232     delete configs_[i];
233 
234   for (uint32_t i = 0; i < sequences_.size(); ++i)
235     delete sequences_[i];
236 }
237 
SetCandidateFilter(uint32_t filter)238 void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
239   if (filter == candidate_filter_) {
240     return;
241   }
242   // We assume the filter will only change from "ALL" to something else.
243   RTC_DCHECK(candidate_filter_ == CF_ALL);
244   candidate_filter_ = filter;
245   for (PortData& port : ports_) {
246     if (!port.has_pairable_candidate()) {
247       continue;
248     }
249     const auto& candidates = port.port()->Candidates();
250     // Setting a filter may cause a ready port to become non-ready
251     // if it no longer has any pairable candidates.
252     if (!std::any_of(candidates.begin(), candidates.end(),
253                      [this, &port](const Candidate& candidate) {
254                        return CandidatePairable(candidate, port.port());
255                      })) {
256       port.set_has_pairable_candidate(false);
257     }
258   }
259 }
260 
StartGettingPorts()261 void BasicPortAllocatorSession::StartGettingPorts() {
262   network_thread_ = rtc::Thread::Current();
263   state_ = SessionState::GATHERING;
264   if (!socket_factory_) {
265     owned_socket_factory_.reset(
266         new rtc::BasicPacketSocketFactory(network_thread_));
267     socket_factory_ = owned_socket_factory_.get();
268   }
269 
270   network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
271 
272   LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
273                << (prune_turn_ports_ ? "enabled" : "disabled");
274 }
275 
StopGettingPorts()276 void BasicPortAllocatorSession::StopGettingPorts() {
277   RTC_DCHECK(rtc::Thread::Current() == network_thread_);
278   ClearGettingPorts();
279   // Note: this must be called after ClearGettingPorts because both may set the
280   // session state and we should set the state to STOPPED.
281   state_ = SessionState::STOPPED;
282 }
283 
ClearGettingPorts()284 void BasicPortAllocatorSession::ClearGettingPorts() {
285   RTC_DCHECK(rtc::Thread::Current() == network_thread_);
286   network_thread_->Clear(this, MSG_ALLOCATE);
287   for (uint32_t i = 0; i < sequences_.size(); ++i) {
288     sequences_[i]->Stop();
289   }
290   network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
291   state_ = SessionState::CLEARED;
292 }
293 
GetFailedNetworks()294 std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
295   std::vector<rtc::Network*> networks = GetNetworks();
296 
297   // A network interface may have both IPv4 and IPv6 networks. Only if
298   // neither of the networks has any connections, the network interface
299   // is considered failed and need to be regathered on.
300   std::set<std::string> networks_with_connection;
301   for (const PortData& data : ports_) {
302     Port* port = data.port();
303     if (!port->connections().empty()) {
304       networks_with_connection.insert(port->Network()->name());
305     }
306   }
307 
308   networks.erase(
309       std::remove_if(networks.begin(), networks.end(),
310                      [networks_with_connection](rtc::Network* network) {
311                        // If a network does not have any connection, it is
312                        // considered failed.
313                        return networks_with_connection.find(network->name()) !=
314                               networks_with_connection.end();
315                      }),
316       networks.end());
317   return networks;
318 }
319 
RegatherOnFailedNetworks()320 void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
321   // Find the list of networks that have no connection.
322   std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
323   if (failed_networks.empty()) {
324     return;
325   }
326 
327   LOG(LS_INFO) << "Regather candidates on failed networks";
328 
329   // Mark a sequence as "network failed" if its network is in the list of failed
330   // networks, so that it won't be considered as equivalent when the session
331   // regathers ports and candidates.
332   for (AllocationSequence* sequence : sequences_) {
333     if (!sequence->network_failed() &&
334         std::find(failed_networks.begin(), failed_networks.end(),
335                   sequence->network()) != failed_networks.end()) {
336       sequence->set_network_failed();
337     }
338   }
339   // Remove ports from being used locally and send signaling to remove
340   // the candidates on the remote side.
341   std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
342   if (!ports_to_prune.empty()) {
343     LOG(LS_INFO) << "Prune " << ports_to_prune.size()
344                  << " ports because their networks failed";
345     PrunePortsAndRemoveCandidates(ports_to_prune);
346   }
347 
348   if (allocation_started_ && network_manager_started_ && !IsStopped()) {
349     SignalIceRegathering(this, IceRegatheringReason::NETWORK_FAILURE);
350 
351     DoAllocate();
352   }
353 }
354 
ReadyPorts() const355 std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
356   std::vector<PortInterface*> ret;
357   for (const PortData& data : ports_) {
358     if (data.ready()) {
359       ret.push_back(data.port());
360     }
361   }
362   return ret;
363 }
364 
ReadyCandidates() const365 std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
366   std::vector<Candidate> candidates;
367   for (const PortData& data : ports_) {
368     if (!data.ready()) {
369       continue;
370     }
371     GetCandidatesFromPort(data, &candidates);
372   }
373   return candidates;
374 }
375 
GetCandidatesFromPort(const PortData & data,std::vector<Candidate> * candidates) const376 void BasicPortAllocatorSession::GetCandidatesFromPort(
377     const PortData& data,
378     std::vector<Candidate>* candidates) const {
379   RTC_CHECK(candidates != nullptr);
380   for (const Candidate& candidate : data.port()->Candidates()) {
381     if (!CheckCandidateFilter(candidate)) {
382       continue;
383     }
384     ProtocolType pvalue;
385     if (!StringToProto(candidate.protocol().c_str(), &pvalue) ||
386         !data.sequence()->ProtocolEnabled(pvalue)) {
387       continue;
388     }
389     candidates->push_back(SanitizeRelatedAddress(candidate));
390   }
391 }
392 
SanitizeRelatedAddress(const Candidate & c) const393 Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
394     const Candidate& c) const {
395   Candidate copy = c;
396   // If adapter enumeration is disabled or host candidates are disabled,
397   // clear the raddr of STUN candidates to avoid local address leakage.
398   bool filter_stun_related_address =
399       ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
400        (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
401       !(candidate_filter_ & CF_HOST);
402   // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
403   // to avoid reflexive address leakage.
404   bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
405   if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
406       (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
407     copy.set_related_address(
408         rtc::EmptySocketAddressWithFamily(copy.address().family()));
409   }
410   return copy;
411 }
412 
CandidatesAllocationDone() const413 bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
414   // Done only if all required AllocationSequence objects
415   // are created.
416   if (!allocation_sequences_created_) {
417     return false;
418   }
419 
420   // Check that all port allocation sequences are complete (not running).
421   if (std::any_of(sequences_.begin(), sequences_.end(),
422                   [](const AllocationSequence* sequence) {
423                     return sequence->state() == AllocationSequence::kRunning;
424                   })) {
425     return false;
426   }
427 
428   // If all allocated ports are no longer gathering, session must have got all
429   // expected candidates. Session will trigger candidates allocation complete
430   // signal.
431   return std::none_of(ports_.begin(), ports_.end(),
432                       [](const PortData& port) { return port.inprogress(); });
433 }
434 
OnMessage(rtc::Message * message)435 void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
436   switch (message->message_id) {
437   case MSG_CONFIG_START:
438     RTC_DCHECK(rtc::Thread::Current() == network_thread_);
439     GetPortConfigurations();
440     break;
441   case MSG_CONFIG_READY:
442     RTC_DCHECK(rtc::Thread::Current() == network_thread_);
443     OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
444     break;
445   case MSG_ALLOCATE:
446     RTC_DCHECK(rtc::Thread::Current() == network_thread_);
447     OnAllocate();
448     break;
449   case MSG_SEQUENCEOBJECTS_CREATED:
450     RTC_DCHECK(rtc::Thread::Current() == network_thread_);
451     OnAllocationSequenceObjectsCreated();
452     break;
453   case MSG_CONFIG_STOP:
454     RTC_DCHECK(rtc::Thread::Current() == network_thread_);
455     OnConfigStop();
456     break;
457   default:
458     RTC_NOTREACHED();
459   }
460 }
461 
UpdateIceParametersInternal()462 void BasicPortAllocatorSession::UpdateIceParametersInternal() {
463   for (PortData& port : ports_) {
464     port.port()->set_content_name(content_name());
465     port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
466   }
467 }
468 
GetPortConfigurations()469 void BasicPortAllocatorSession::GetPortConfigurations() {
470   PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
471                                                     username(),
472                                                     password());
473 
474   for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
475     config->AddRelay(turn_server);
476   }
477   ConfigReady(config);
478 }
479 
ConfigReady(PortConfiguration * config)480 void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
481   network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
482 }
483 
484 // Adds a configuration to the list.
OnConfigReady(PortConfiguration * config)485 void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
486   if (config) {
487     configs_.push_back(config);
488   }
489 
490   AllocatePorts();
491 }
492 
OnConfigStop()493 void BasicPortAllocatorSession::OnConfigStop() {
494   RTC_DCHECK(rtc::Thread::Current() == network_thread_);
495 
496   // If any of the allocated ports have not completed the candidates allocation,
497   // mark those as error. Since session doesn't need any new candidates
498   // at this stage of the allocation, it's safe to discard any new candidates.
499   bool send_signal = false;
500   for (std::vector<PortData>::iterator it = ports_.begin();
501        it != ports_.end(); ++it) {
502     if (it->inprogress()) {
503       // Updating port state to error, which didn't finish allocating candidates
504       // yet.
505       it->set_error();
506       send_signal = true;
507     }
508   }
509 
510   // Did we stop any running sequences?
511   for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
512        it != sequences_.end() && !send_signal; ++it) {
513     if ((*it)->state() == AllocationSequence::kStopped) {
514       send_signal = true;
515     }
516   }
517 
518   // If we stopped anything that was running, send a done signal now.
519   if (send_signal) {
520     MaybeSignalCandidatesAllocationDone();
521   }
522 }
523 
AllocatePorts()524 void BasicPortAllocatorSession::AllocatePorts() {
525   RTC_DCHECK(rtc::Thread::Current() == network_thread_);
526   network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
527 }
528 
OnAllocate()529 void BasicPortAllocatorSession::OnAllocate() {
530   if (network_manager_started_ && !IsStopped())
531     DoAllocate();
532 
533   allocation_started_ = true;
534 }
535 
GetNetworks()536 std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
537   std::vector<rtc::Network*> networks;
538   rtc::NetworkManager* network_manager = allocator_->network_manager();
539   RTC_DCHECK(network_manager != nullptr);
540   // If the network permission state is BLOCKED, we just act as if the flag has
541   // been passed in.
542   if (network_manager->enumeration_permission() ==
543       rtc::NetworkManager::ENUMERATION_BLOCKED) {
544     set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
545   }
546   // If the adapter enumeration is disabled, we'll just bind to any address
547   // instead of specific NIC. This is to ensure the same routing for http
548   // traffic by OS is also used here to avoid any local or public IP leakage
549   // during stun process.
550   if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
551     network_manager->GetAnyAddressNetworks(&networks);
552   } else {
553     network_manager->GetNetworks(&networks);
554     // If network enumeration fails, use the ANY address as a fallback, so we
555     // can at least try gathering candidates using the default route chosen by
556     // the OS.
557     if (networks.empty()) {
558       network_manager->GetAnyAddressNetworks(&networks);
559     }
560   }
561   networks.erase(std::remove_if(networks.begin(), networks.end(),
562                                 [this](rtc::Network* network) {
563                                   return allocator_->network_ignore_mask() &
564                                          network->type();
565                                 }),
566                  networks.end());
567 
568   if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
569     uint16_t lowest_cost = rtc::kNetworkCostMax;
570     for (rtc::Network* network : networks) {
571       lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
572     }
573     networks.erase(std::remove_if(networks.begin(), networks.end(),
574                                   [lowest_cost](rtc::Network* network) {
575                                     return network->GetCost() >
576                                            lowest_cost + rtc::kNetworkCostLow;
577                                   }),
578                    networks.end());
579   }
580   return networks;
581 }
582 
583 // For each network, see if we have a sequence that covers it already.  If not,
584 // create a new sequence to create the appropriate ports.
DoAllocate()585 void BasicPortAllocatorSession::DoAllocate() {
586   bool done_signal_needed = false;
587   std::vector<rtc::Network*> networks = GetNetworks();
588   if (networks.empty()) {
589     LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
590     done_signal_needed = true;
591   } else {
592     LOG(LS_INFO) << "Allocate ports on "<< networks.size() << " networks";
593     PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
594     for (uint32_t i = 0; i < networks.size(); ++i) {
595       uint32_t sequence_flags = flags();
596       if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
597         // If all the ports are disabled we should just fire the allocation
598         // done event and return.
599         done_signal_needed = true;
600         break;
601       }
602 
603       if (!config || config->relays.empty()) {
604         // No relay ports specified in this config.
605         sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
606       }
607 
608       if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
609           networks[i]->GetBestIP().family() == AF_INET6) {
610         // Skip IPv6 networks unless the flag's been set.
611         continue;
612       }
613 
614       // Disable phases that would only create ports equivalent to
615       // ones that we have already made.
616       DisableEquivalentPhases(networks[i], config, &sequence_flags);
617 
618       if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
619         // New AllocationSequence would have nothing to do, so don't make it.
620         continue;
621       }
622 
623       AllocationSequence* sequence =
624           new AllocationSequence(this, networks[i], config, sequence_flags);
625       sequence->SignalPortAllocationComplete.connect(
626           this, &BasicPortAllocatorSession::OnPortAllocationComplete);
627       sequence->Init();
628       sequence->Start();
629       sequences_.push_back(sequence);
630       done_signal_needed = true;
631     }
632   }
633   if (done_signal_needed) {
634     network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
635   }
636 }
637 
OnNetworksChanged()638 void BasicPortAllocatorSession::OnNetworksChanged() {
639   std::vector<rtc::Network*> networks = GetNetworks();
640   std::vector<rtc::Network*> failed_networks;
641   for (AllocationSequence* sequence : sequences_) {
642     // Mark the sequence as "network failed" if its network is not in
643     // |networks|.
644     if (!sequence->network_failed() &&
645         std::find(networks.begin(), networks.end(), sequence->network()) ==
646             networks.end()) {
647       sequence->OnNetworkFailed();
648       failed_networks.push_back(sequence->network());
649     }
650   }
651   std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
652   if (!ports_to_prune.empty()) {
653     LOG(LS_INFO) << "Prune " << ports_to_prune.size()
654                  << " ports because their networks were gone";
655     PrunePortsAndRemoveCandidates(ports_to_prune);
656   }
657 
658   if (allocation_started_ && !IsStopped()) {
659     if (network_manager_started_) {
660       // If the network manager has started, it must be regathering.
661       SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
662     }
663     DoAllocate();
664   }
665 
666   if (!network_manager_started_) {
667     LOG(LS_INFO) << "Network manager has started";
668     network_manager_started_ = true;
669   }
670 }
671 
DisableEquivalentPhases(rtc::Network * network,PortConfiguration * config,uint32_t * flags)672 void BasicPortAllocatorSession::DisableEquivalentPhases(
673     rtc::Network* network,
674     PortConfiguration* config,
675     uint32_t* flags) {
676   for (uint32_t i = 0; i < sequences_.size() &&
677                            (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
678        ++i) {
679     sequences_[i]->DisableEquivalentPhases(network, config, flags);
680   }
681 }
682 
AddAllocatedPort(Port * port,AllocationSequence * seq,bool prepare_address)683 void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
684                                                  AllocationSequence * seq,
685                                                  bool prepare_address) {
686   if (!port)
687     return;
688 
689   LOG(LS_INFO) << "Adding allocated port for " << content_name();
690   port->set_content_name(content_name());
691   port->set_component(component());
692   port->set_generation(generation());
693   if (allocator_->proxy().type != rtc::PROXY_NONE)
694     port->set_proxy(allocator_->user_agent(), allocator_->proxy());
695   port->set_send_retransmit_count_attribute(
696       (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
697 
698   PortData data(port, seq);
699   ports_.push_back(data);
700 
701   port->SignalCandidateReady.connect(
702       this, &BasicPortAllocatorSession::OnCandidateReady);
703   port->SignalPortComplete.connect(this,
704       &BasicPortAllocatorSession::OnPortComplete);
705   port->SignalDestroyed.connect(this,
706       &BasicPortAllocatorSession::OnPortDestroyed);
707   port->SignalPortError.connect(
708       this, &BasicPortAllocatorSession::OnPortError);
709   LOG_J(LS_INFO, port) << "Added port to allocator";
710 
711   if (prepare_address)
712     port->PrepareAddress();
713 }
714 
OnAllocationSequenceObjectsCreated()715 void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
716   allocation_sequences_created_ = true;
717   // Send candidate allocation complete signal if we have no sequences.
718   MaybeSignalCandidatesAllocationDone();
719 }
720 
OnCandidateReady(Port * port,const Candidate & c)721 void BasicPortAllocatorSession::OnCandidateReady(
722     Port* port, const Candidate& c) {
723   RTC_DCHECK(rtc::Thread::Current() == network_thread_);
724   PortData* data = FindPort(port);
725   RTC_DCHECK(data != NULL);
726   LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
727   // Discarding any candidate signal if port allocation status is
728   // already done with gathering.
729   if (!data->inprogress()) {
730     LOG(LS_WARNING)
731         << "Discarding candidate because port is already done gathering.";
732     return;
733   }
734 
735   // Mark that the port has a pairable candidate, either because we have a
736   // usable candidate from the port, or simply because the port is bound to the
737   // any address and therefore has no host candidate. This will trigger the port
738   // to start creating candidate pairs (connections) and issue connectivity
739   // checks. If port has already been marked as having a pairable candidate,
740   // do nothing here.
741   // Note: We should check whether any candidates may become ready after this
742   // because there we will check whether the candidate is generated by the ready
743   // ports, which may include this port.
744   bool pruned = false;
745   if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
746     data->set_has_pairable_candidate(true);
747 
748     if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
749       pruned = PruneTurnPorts(port);
750     }
751     // If the current port is not pruned yet, SignalPortReady.
752     if (!data->pruned()) {
753       LOG_J(LS_INFO, port) << "Port ready.";
754       SignalPortReady(this, port);
755       port->KeepAliveUntilPruned();
756     }
757   }
758 
759   ProtocolType pvalue;
760   bool candidate_protocol_enabled =
761       StringToProto(c.protocol().c_str(), &pvalue) &&
762       data->sequence()->ProtocolEnabled(pvalue);
763 
764   if (data->ready() && CheckCandidateFilter(c) && candidate_protocol_enabled) {
765     std::vector<Candidate> candidates;
766     candidates.push_back(SanitizeRelatedAddress(c));
767     SignalCandidatesReady(this, candidates);
768   } else if (!candidate_protocol_enabled) {
769     LOG(LS_INFO)
770         << "Not yet signaling candidate because protocol is not yet enabled.";
771   } else {
772     LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
773   }
774 
775   // If we have pruned any port, maybe need to signal port allocation done.
776   if (pruned) {
777     MaybeSignalCandidatesAllocationDone();
778   }
779 }
780 
GetBestTurnPortForNetwork(const std::string & network_name) const781 Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
782     const std::string& network_name) const {
783   Port* best_turn_port = nullptr;
784   for (const PortData& data : ports_) {
785     if (data.port()->Network()->name() == network_name &&
786         data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
787         (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
788       best_turn_port = data.port();
789     }
790   }
791   return best_turn_port;
792 }
793 
PruneTurnPorts(Port * newly_pairable_turn_port)794 bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
795   // Note: We determine the same network based only on their network names. So
796   // if an IPv4 address and an IPv6 address have the same network name, they
797   // are considered the same network here.
798   const std::string& network_name = newly_pairable_turn_port->Network()->name();
799   Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
800   // |port| is already in the list of ports, so the best port cannot be nullptr.
801   RTC_CHECK(best_turn_port != nullptr);
802 
803   bool pruned = false;
804   std::vector<PortData*> ports_to_prune;
805   for (PortData& data : ports_) {
806     if (data.port()->Network()->name() == network_name &&
807         data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
808         ComparePort(data.port(), best_turn_port) < 0) {
809       pruned = true;
810       if (data.port() != newly_pairable_turn_port) {
811         // These ports will be pruned in PrunePortsAndRemoveCandidates.
812         ports_to_prune.push_back(&data);
813       } else {
814         data.Prune();
815       }
816     }
817   }
818 
819   if (!ports_to_prune.empty()) {
820     LOG(LS_INFO) << "Prune " << ports_to_prune.size()
821                  << " low-priority TURN ports";
822     PrunePortsAndRemoveCandidates(ports_to_prune);
823   }
824   return pruned;
825 }
826 
PruneAllPorts()827 void BasicPortAllocatorSession::PruneAllPorts() {
828   for (PortData& data : ports_) {
829     data.Prune();
830   }
831 }
832 
OnPortComplete(Port * port)833 void BasicPortAllocatorSession::OnPortComplete(Port* port) {
834   RTC_DCHECK(rtc::Thread::Current() == network_thread_);
835   LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
836   PortData* data = FindPort(port);
837   RTC_DCHECK(data != NULL);
838 
839   // Ignore any late signals.
840   if (!data->inprogress()) {
841     return;
842   }
843 
844   // Moving to COMPLETE state.
845   data->set_complete();
846   // Send candidate allocation complete signal if this was the last port.
847   MaybeSignalCandidatesAllocationDone();
848 }
849 
OnPortError(Port * port)850 void BasicPortAllocatorSession::OnPortError(Port* port) {
851   RTC_DCHECK(rtc::Thread::Current() == network_thread_);
852   LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
853   PortData* data = FindPort(port);
854   RTC_DCHECK(data != NULL);
855   // We might have already given up on this port and stopped it.
856   if (!data->inprogress()) {
857     return;
858   }
859 
860   // SignalAddressError is currently sent from StunPort/TurnPort.
861   // But this signal itself is generic.
862   data->set_error();
863   // Send candidate allocation complete signal if this was the last port.
864   MaybeSignalCandidatesAllocationDone();
865 }
866 
OnProtocolEnabled(AllocationSequence * seq,ProtocolType proto)867 void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
868                                                   ProtocolType proto) {
869   std::vector<Candidate> candidates;
870   for (std::vector<PortData>::iterator it = ports_.begin();
871        it != ports_.end(); ++it) {
872     if (it->sequence() != seq)
873       continue;
874 
875     const std::vector<Candidate>& potentials = it->port()->Candidates();
876     for (size_t i = 0; i < potentials.size(); ++i) {
877       if (!CheckCandidateFilter(potentials[i])) {
878         continue;
879       }
880       ProtocolType pvalue;
881       bool candidate_protocol_enabled =
882           StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
883           pvalue == proto;
884       if (candidate_protocol_enabled) {
885         LOG(LS_INFO) << "Signaling candidate because protocol was enabled: "
886                      << potentials[i].ToSensitiveString();
887         candidates.push_back(potentials[i]);
888       }
889     }
890   }
891 
892   if (!candidates.empty()) {
893     SignalCandidatesReady(this, candidates);
894   }
895 }
896 
CheckCandidateFilter(const Candidate & c) const897 bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
898   uint32_t filter = candidate_filter_;
899 
900   // When binding to any address, before sending packets out, the getsockname
901   // returns all 0s, but after sending packets, it'll be the NIC used to
902   // send. All 0s is not a valid ICE candidate address and should be filtered
903   // out.
904   if (c.address().IsAnyIP()) {
905     return false;
906   }
907 
908   if (c.type() == RELAY_PORT_TYPE) {
909     return ((filter & CF_RELAY) != 0);
910   } else if (c.type() == STUN_PORT_TYPE) {
911     return ((filter & CF_REFLEXIVE) != 0);
912   } else if (c.type() == LOCAL_PORT_TYPE) {
913     if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
914       // We allow host candidates if the filter allows server-reflexive
915       // candidates and the candidate is a public IP. Because we don't generate
916       // server-reflexive candidates if they have the same IP as the host
917       // candidate (i.e. when the host candidate is a public IP), filtering to
918       // only server-reflexive candidates won't work right when the host
919       // candidates have public IPs.
920       return true;
921     }
922 
923     return ((filter & CF_HOST) != 0);
924   }
925   return false;
926 }
927 
CandidatePairable(const Candidate & c,const Port * port) const928 bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
929                                                   const Port* port) const {
930   bool candidate_signalable = CheckCandidateFilter(c);
931 
932   // When device enumeration is disabled (to prevent non-default IP addresses
933   // from leaking), we ping from some local candidates even though we don't
934   // signal them. However, if host candidates are also disabled (for example, to
935   // prevent even default IP addresses from leaking), we still don't want to
936   // ping from them, even if device enumeration is disabled.  Thus, we check for
937   // both device enumeration and host candidates being disabled.
938   bool network_enumeration_disabled = c.address().IsAnyIP();
939   bool can_ping_from_candidate =
940       (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
941   bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
942 
943   return candidate_signalable ||
944          (network_enumeration_disabled && can_ping_from_candidate &&
945           !host_candidates_disabled);
946 }
947 
OnPortAllocationComplete(AllocationSequence * seq)948 void BasicPortAllocatorSession::OnPortAllocationComplete(
949     AllocationSequence* seq) {
950   // Send candidate allocation complete signal if all ports are done.
951   MaybeSignalCandidatesAllocationDone();
952 }
953 
MaybeSignalCandidatesAllocationDone()954 void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
955   if (CandidatesAllocationDone()) {
956     if (pooled()) {
957       LOG(LS_INFO) << "All candidates gathered for pooled session.";
958     } else {
959       LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
960                    << component() << ":" << generation();
961     }
962     SignalCandidatesAllocationDone(this);
963   }
964 }
965 
OnPortDestroyed(PortInterface * port)966 void BasicPortAllocatorSession::OnPortDestroyed(
967     PortInterface* port) {
968   RTC_DCHECK(rtc::Thread::Current() == network_thread_);
969   for (std::vector<PortData>::iterator iter = ports_.begin();
970        iter != ports_.end(); ++iter) {
971     if (port == iter->port()) {
972       ports_.erase(iter);
973       LOG_J(LS_INFO, port) << "Removed port from allocator ("
974                            << static_cast<int>(ports_.size()) << " remaining)";
975       return;
976     }
977   }
978   RTC_NOTREACHED();
979 }
980 
FindPort(Port * port)981 BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
982     Port* port) {
983   for (std::vector<PortData>::iterator it = ports_.begin();
984        it != ports_.end(); ++it) {
985     if (it->port() == port) {
986       return &*it;
987     }
988   }
989   return NULL;
990 }
991 
992 std::vector<BasicPortAllocatorSession::PortData*>
GetUnprunedPorts(const std::vector<rtc::Network * > & networks)993 BasicPortAllocatorSession::GetUnprunedPorts(
994     const std::vector<rtc::Network*>& networks) {
995   std::vector<PortData*> unpruned_ports;
996   for (PortData& port : ports_) {
997     if (!port.pruned() &&
998         std::find(networks.begin(), networks.end(),
999                   port.sequence()->network()) != networks.end()) {
1000       unpruned_ports.push_back(&port);
1001     }
1002   }
1003   return unpruned_ports;
1004 }
1005 
PrunePortsAndRemoveCandidates(const std::vector<PortData * > & port_data_list)1006 void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1007     const std::vector<PortData*>& port_data_list) {
1008   std::vector<PortInterface*> pruned_ports;
1009   std::vector<Candidate> removed_candidates;
1010   for (PortData* data : port_data_list) {
1011     // Prune the port so that it may be destroyed.
1012     data->Prune();
1013     pruned_ports.push_back(data->port());
1014     if (data->has_pairable_candidate()) {
1015       GetCandidatesFromPort(*data, &removed_candidates);
1016       // Mark the port as having no pairable candidates so that its candidates
1017       // won't be removed multiple times.
1018       data->set_has_pairable_candidate(false);
1019     }
1020   }
1021   if (!pruned_ports.empty()) {
1022     SignalPortsPruned(this, pruned_ports);
1023   }
1024   if (!removed_candidates.empty()) {
1025     LOG(LS_INFO) << "Removed " << removed_candidates.size() << " candidates";
1026     SignalCandidatesRemoved(this, removed_candidates);
1027   }
1028 }
1029 
1030 // AllocationSequence
1031 
AllocationSequence(BasicPortAllocatorSession * session,rtc::Network * network,PortConfiguration * config,uint32_t flags)1032 AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1033                                        rtc::Network* network,
1034                                        PortConfiguration* config,
1035                                        uint32_t flags)
1036     : session_(session),
1037       network_(network),
1038       ip_(network->GetBestIP()),
1039       config_(config),
1040       state_(kInit),
1041       flags_(flags),
1042       udp_socket_(),
1043       udp_port_(NULL),
1044       phase_(0) {
1045 }
1046 
Init()1047 void AllocationSequence::Init() {
1048   if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1049     udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
1050         rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
1051         session_->allocator()->max_port()));
1052     if (udp_socket_) {
1053       udp_socket_->SignalReadPacket.connect(
1054           this, &AllocationSequence::OnReadPacket);
1055     }
1056     // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1057     // are next available options to setup a communication channel.
1058   }
1059 }
1060 
Clear()1061 void AllocationSequence::Clear() {
1062   udp_port_ = NULL;
1063   turn_ports_.clear();
1064 }
1065 
OnNetworkFailed()1066 void AllocationSequence::OnNetworkFailed() {
1067   RTC_DCHECK(!network_failed_);
1068   network_failed_ = true;
1069   // Stop the allocation sequence if its network failed.
1070   Stop();
1071 }
1072 
~AllocationSequence()1073 AllocationSequence::~AllocationSequence() {
1074   session_->network_thread()->Clear(this);
1075 }
1076 
DisableEquivalentPhases(rtc::Network * network,PortConfiguration * config,uint32_t * flags)1077 void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
1078     PortConfiguration* config, uint32_t* flags) {
1079   if (network_failed_) {
1080     // If the network of this allocation sequence has ever become failed,
1081     // it won't be equivalent to the new network.
1082     return;
1083   }
1084 
1085   if (!((network == network_) && (ip_ == network->GetBestIP()))) {
1086     // Different network setup; nothing is equivalent.
1087     return;
1088   }
1089 
1090   // Else turn off the stuff that we've already got covered.
1091 
1092   // Every config implicitly specifies local, so turn that off right away.
1093   *flags |= PORTALLOCATOR_DISABLE_UDP;
1094   *flags |= PORTALLOCATOR_DISABLE_TCP;
1095 
1096   if (config_ && config) {
1097     if (config_->StunServers() == config->StunServers()) {
1098       // Already got this STUN servers covered.
1099       *flags |= PORTALLOCATOR_DISABLE_STUN;
1100     }
1101     if (!config_->relays.empty()) {
1102       // Already got relays covered.
1103       // NOTE: This will even skip a _different_ set of relay servers if we
1104       // were to be given one, but that never happens in our codebase. Should
1105       // probably get rid of the list in PortConfiguration and just keep a
1106       // single relay server in each one.
1107       *flags |= PORTALLOCATOR_DISABLE_RELAY;
1108     }
1109   }
1110 }
1111 
Start()1112 void AllocationSequence::Start() {
1113   state_ = kRunning;
1114   session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
1115 }
1116 
Stop()1117 void AllocationSequence::Stop() {
1118   // If the port is completed, don't set it to stopped.
1119   if (state_ == kRunning) {
1120     state_ = kStopped;
1121     session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1122   }
1123 }
1124 
OnMessage(rtc::Message * msg)1125 void AllocationSequence::OnMessage(rtc::Message* msg) {
1126   RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1127   RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
1128 
1129   const char* const PHASE_NAMES[kNumPhases] = {
1130     "Udp", "Relay", "Tcp", "SslTcp"
1131   };
1132 
1133   // Perform all of the phases in the current step.
1134   LOG_J(LS_INFO, network_) << "Allocation Phase="
1135                            << PHASE_NAMES[phase_];
1136 
1137   switch (phase_) {
1138     case PHASE_UDP:
1139       CreateUDPPorts();
1140       CreateStunPorts();
1141       EnableProtocol(PROTO_UDP);
1142       break;
1143 
1144     case PHASE_RELAY:
1145       CreateRelayPorts();
1146       break;
1147 
1148     case PHASE_TCP:
1149       CreateTCPPorts();
1150       EnableProtocol(PROTO_TCP);
1151       break;
1152 
1153     case PHASE_SSLTCP:
1154       state_ = kCompleted;
1155       EnableProtocol(PROTO_SSLTCP);
1156       break;
1157 
1158     default:
1159       RTC_NOTREACHED();
1160   }
1161 
1162   if (state() == kRunning) {
1163     ++phase_;
1164     session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1165                                             session_->allocator()->step_delay(),
1166                                             this, MSG_ALLOCATION_PHASE);
1167   } else {
1168     // If all phases in AllocationSequence are completed, no allocation
1169     // steps needed further. Canceling  pending signal.
1170     session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1171     SignalPortAllocationComplete(this);
1172   }
1173 }
1174 
EnableProtocol(ProtocolType proto)1175 void AllocationSequence::EnableProtocol(ProtocolType proto) {
1176   if (!ProtocolEnabled(proto)) {
1177     protocols_.push_back(proto);
1178     session_->OnProtocolEnabled(this, proto);
1179   }
1180 }
1181 
ProtocolEnabled(ProtocolType proto) const1182 bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
1183   for (ProtocolList::const_iterator it = protocols_.begin();
1184        it != protocols_.end(); ++it) {
1185     if (*it == proto)
1186       return true;
1187   }
1188   return false;
1189 }
1190 
CreateUDPPorts()1191 void AllocationSequence::CreateUDPPorts() {
1192   if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1193     LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1194     return;
1195   }
1196 
1197   // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1198   // is enabled completely.
1199   UDPPort* port = NULL;
1200   bool emit_local_candidate_for_anyaddress =
1201       !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
1202   if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
1203     port = UDPPort::Create(
1204         session_->network_thread(), session_->socket_factory(), network_,
1205         udp_socket_.get(), session_->username(), session_->password(),
1206         session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
1207   } else {
1208     port = UDPPort::Create(
1209         session_->network_thread(), session_->socket_factory(), network_, ip_,
1210         session_->allocator()->min_port(), session_->allocator()->max_port(),
1211         session_->username(), session_->password(),
1212         session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
1213   }
1214 
1215   if (port) {
1216     // If shared socket is enabled, STUN candidate will be allocated by the
1217     // UDPPort.
1218     if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1219       udp_port_ = port;
1220       port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1221 
1222       // If STUN is not disabled, setting stun server address to port.
1223       if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1224         if (config_ && !config_->StunServers().empty()) {
1225           LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1226                        <<  "STUN candidate generation.";
1227           port->set_server_addresses(config_->StunServers());
1228         }
1229       }
1230     }
1231 
1232     session_->AddAllocatedPort(port, this, true);
1233   }
1234 }
1235 
CreateTCPPorts()1236 void AllocationSequence::CreateTCPPorts() {
1237   if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1238     LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1239     return;
1240   }
1241 
1242   Port* port = TCPPort::Create(session_->network_thread(),
1243                                session_->socket_factory(),
1244                                network_, ip_,
1245                                session_->allocator()->min_port(),
1246                                session_->allocator()->max_port(),
1247                                session_->username(), session_->password(),
1248                                session_->allocator()->allow_tcp_listen());
1249   if (port) {
1250     session_->AddAllocatedPort(port, this, true);
1251     // Since TCPPort is not created using shared socket, |port| will not be
1252     // added to the dequeue.
1253   }
1254 }
1255 
CreateStunPorts()1256 void AllocationSequence::CreateStunPorts() {
1257   if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1258     LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1259     return;
1260   }
1261 
1262   if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1263     return;
1264   }
1265 
1266   if (!(config_ && !config_->StunServers().empty())) {
1267     LOG(LS_WARNING)
1268         << "AllocationSequence: No STUN server configured, skipping.";
1269     return;
1270   }
1271 
1272   StunPort* port = StunPort::Create(session_->network_thread(),
1273                                 session_->socket_factory(),
1274                                 network_, ip_,
1275                                 session_->allocator()->min_port(),
1276                                 session_->allocator()->max_port(),
1277                                 session_->username(), session_->password(),
1278                                 config_->StunServers(),
1279                                 session_->allocator()->origin());
1280   if (port) {
1281     session_->AddAllocatedPort(port, this, true);
1282     // Since StunPort is not created using shared socket, |port| will not be
1283     // added to the dequeue.
1284   }
1285 }
1286 
CreateRelayPorts()1287 void AllocationSequence::CreateRelayPorts() {
1288   if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1289      LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1290      return;
1291   }
1292 
1293   // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1294   // ought to have a relay list for them here.
1295   RTC_DCHECK(config_ && !config_->relays.empty());
1296   if (!(config_ && !config_->relays.empty())) {
1297     LOG(LS_WARNING)
1298         << "AllocationSequence: No relay server configured, skipping.";
1299     return;
1300   }
1301 
1302   for (RelayServerConfig& relay : config_->relays) {
1303     if (relay.type == RELAY_GTURN) {
1304       CreateGturnPort(relay);
1305     } else if (relay.type == RELAY_TURN) {
1306       CreateTurnPort(relay);
1307     } else {
1308       RTC_NOTREACHED();
1309     }
1310   }
1311 }
1312 
CreateGturnPort(const RelayServerConfig & config)1313 void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1314   // TODO(mallinath) - Rename RelayPort to GTurnPort.
1315   RelayPort* port = RelayPort::Create(session_->network_thread(),
1316                                       session_->socket_factory(),
1317                                       network_, ip_,
1318                                       session_->allocator()->min_port(),
1319                                       session_->allocator()->max_port(),
1320                                       config_->username, config_->password);
1321   if (port) {
1322     // Since RelayPort is not created using shared socket, |port| will not be
1323     // added to the dequeue.
1324     // Note: We must add the allocated port before we add addresses because
1325     //       the latter will create candidates that need name and preference
1326     //       settings.  However, we also can't prepare the address (normally
1327     //       done by AddAllocatedPort) until we have these addresses.  So we
1328     //       wait to do that until below.
1329     session_->AddAllocatedPort(port, this, false);
1330 
1331     // Add the addresses of this protocol.
1332     PortList::const_iterator relay_port;
1333     for (relay_port = config.ports.begin();
1334          relay_port != config.ports.end();
1335          ++relay_port) {
1336       port->AddServerAddress(*relay_port);
1337       port->AddExternalAddress(*relay_port);
1338     }
1339     // Start fetching an address for this port.
1340     port->PrepareAddress();
1341   }
1342 }
1343 
CreateTurnPort(const RelayServerConfig & config)1344 void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1345   PortList::const_iterator relay_port;
1346   for (relay_port = config.ports.begin();
1347        relay_port != config.ports.end(); ++relay_port) {
1348     TurnPort* port = NULL;
1349 
1350     // Skip UDP connections to relay servers if it's disallowed.
1351     if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1352         relay_port->proto == PROTO_UDP) {
1353       continue;
1354     }
1355 
1356     // Do not create a port if the server address family is known and does
1357     // not match the local IP address family.
1358     int server_ip_family = relay_port->address.ipaddr().family();
1359     int local_ip_family = ip_.family();
1360     if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1361       LOG(LS_INFO) << "Server and local address families are not compatible. "
1362                    << "Server address: "
1363                    << relay_port->address.ipaddr().ToString()
1364                    << " Local address: " << ip_.ToString();
1365       continue;
1366     }
1367 
1368 
1369     // Shared socket mode must be enabled only for UDP based ports. Hence
1370     // don't pass shared socket for ports which will create TCP sockets.
1371     // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1372     // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1373     if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
1374         relay_port->proto == PROTO_UDP && udp_socket_) {
1375       port = TurnPort::Create(session_->network_thread(),
1376                               session_->socket_factory(),
1377                               network_, udp_socket_.get(),
1378                               session_->username(), session_->password(),
1379                               *relay_port, config.credentials, config.priority,
1380                               session_->allocator()->origin());
1381       turn_ports_.push_back(port);
1382       // Listen to the port destroyed signal, to allow AllocationSequence to
1383       // remove entrt from it's map.
1384       port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1385     } else {
1386       port = TurnPort::Create(session_->network_thread(),
1387                               session_->socket_factory(),
1388                               network_, ip_,
1389                               session_->allocator()->min_port(),
1390                               session_->allocator()->max_port(),
1391                               session_->username(),
1392                               session_->password(),
1393                               *relay_port, config.credentials, config.priority,
1394                               session_->allocator()->origin());
1395     }
1396     RTC_DCHECK(port != NULL);
1397     port->SetTlsCertPolicy(config.tls_cert_policy);
1398     session_->AddAllocatedPort(port, this, true);
1399   }
1400 }
1401 
OnReadPacket(rtc::AsyncPacketSocket * socket,const char * data,size_t size,const rtc::SocketAddress & remote_addr,const rtc::PacketTime & packet_time)1402 void AllocationSequence::OnReadPacket(
1403     rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1404     const rtc::SocketAddress& remote_addr,
1405     const rtc::PacketTime& packet_time) {
1406   RTC_DCHECK(socket == udp_socket_.get());
1407 
1408   bool turn_port_found = false;
1409 
1410   // Try to find the TurnPort that matches the remote address. Note that the
1411   // message could be a STUN binding response if the TURN server is also used as
1412   // a STUN server. We don't want to parse every message here to check if it is
1413   // a STUN binding response, so we pass the message to TurnPort regardless of
1414   // the message type. The TurnPort will just ignore the message since it will
1415   // not find any request by transaction ID.
1416   for (TurnPort* port : turn_ports_) {
1417     if (port->server_address().address == remote_addr) {
1418       if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1419                                      packet_time)) {
1420         return;
1421       }
1422       turn_port_found = true;
1423     }
1424   }
1425 
1426   if (udp_port_) {
1427     const ServerAddresses& stun_servers = udp_port_->server_addresses();
1428 
1429     // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1430     // the TURN server is also a STUN server.
1431     if (!turn_port_found ||
1432         stun_servers.find(remote_addr) != stun_servers.end()) {
1433       RTC_DCHECK(udp_port_->SharedSocket());
1434       udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1435                                       packet_time);
1436     }
1437   }
1438 }
1439 
OnPortDestroyed(PortInterface * port)1440 void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1441   if (udp_port_ == port) {
1442     udp_port_ = NULL;
1443     return;
1444   }
1445 
1446   auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1447   if (it != turn_ports_.end()) {
1448     turn_ports_.erase(it);
1449   } else {
1450     LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1451     RTC_NOTREACHED();
1452   }
1453 }
1454 
1455 // PortConfiguration
PortConfiguration(const rtc::SocketAddress & stun_address,const std::string & username,const std::string & password)1456 PortConfiguration::PortConfiguration(
1457     const rtc::SocketAddress& stun_address,
1458     const std::string& username,
1459     const std::string& password)
1460     : stun_address(stun_address), username(username), password(password) {
1461   if (!stun_address.IsNil())
1462     stun_servers.insert(stun_address);
1463 }
1464 
PortConfiguration(const ServerAddresses & stun_servers,const std::string & username,const std::string & password)1465 PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1466                                      const std::string& username,
1467                                      const std::string& password)
1468     : stun_servers(stun_servers),
1469       username(username),
1470       password(password) {
1471   if (!stun_servers.empty())
1472     stun_address = *(stun_servers.begin());
1473 }
1474 
StunServers()1475 ServerAddresses PortConfiguration::StunServers() {
1476   if (!stun_address.IsNil() &&
1477       stun_servers.find(stun_address) == stun_servers.end()) {
1478     stun_servers.insert(stun_address);
1479   }
1480   // Every UDP TURN server should also be used as a STUN server.
1481   ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1482   for (const rtc::SocketAddress& turn_server : turn_servers) {
1483     if (stun_servers.find(turn_server) == stun_servers.end()) {
1484       stun_servers.insert(turn_server);
1485     }
1486   }
1487   return stun_servers;
1488 }
1489 
AddRelay(const RelayServerConfig & config)1490 void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1491   relays.push_back(config);
1492 }
1493 
SupportsProtocol(const RelayServerConfig & relay,ProtocolType type) const1494 bool PortConfiguration::SupportsProtocol(
1495     const RelayServerConfig& relay, ProtocolType type) const {
1496   PortList::const_iterator relay_port;
1497   for (relay_port = relay.ports.begin();
1498         relay_port != relay.ports.end();
1499         ++relay_port) {
1500     if (relay_port->proto == type)
1501       return true;
1502   }
1503   return false;
1504 }
1505 
SupportsProtocol(RelayType turn_type,ProtocolType type) const1506 bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1507                                          ProtocolType type) const {
1508   for (size_t i = 0; i < relays.size(); ++i) {
1509     if (relays[i].type == turn_type &&
1510         SupportsProtocol(relays[i], type))
1511       return true;
1512   }
1513   return false;
1514 }
1515 
GetRelayServerAddresses(RelayType turn_type,ProtocolType type) const1516 ServerAddresses PortConfiguration::GetRelayServerAddresses(
1517     RelayType turn_type, ProtocolType type) const {
1518   ServerAddresses servers;
1519   for (size_t i = 0; i < relays.size(); ++i) {
1520     if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1521       servers.insert(relays[i].ports.front().address);
1522     }
1523   }
1524   return servers;
1525 }
1526 
1527 }  // namespace cricket
1528