1 /*
2  *  Copyright 2012 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 "api/jsep_session_description.h"
12 
13 #include <memory>
14 
15 #include "p2p/base/port.h"
16 #include "pc/media_session.h"
17 #include "pc/webrtc_sdp.h"
18 #include "rtc_base/arraysize.h"
19 
20 using cricket::SessionDescription;
21 
22 namespace webrtc {
23 namespace {
24 
25 // RFC 5245
26 // It is RECOMMENDED that default candidates be chosen based on the
27 // likelihood of those candidates to work with the peer that is being
28 // contacted.  It is RECOMMENDED that relayed > reflexive > host.
29 constexpr int kPreferenceUnknown = 0;
30 constexpr int kPreferenceHost = 1;
31 constexpr int kPreferenceReflexive = 2;
32 constexpr int kPreferenceRelayed = 3;
33 
34 constexpr char kDummyAddress[] = "0.0.0.0";
35 constexpr int kDummyPort = 9;
36 
GetCandidatePreferenceFromType(const std::string & type)37 int GetCandidatePreferenceFromType(const std::string& type) {
38   int preference = kPreferenceUnknown;
39   if (type == cricket::LOCAL_PORT_TYPE) {
40     preference = kPreferenceHost;
41   } else if (type == cricket::STUN_PORT_TYPE) {
42     preference = kPreferenceReflexive;
43   } else if (type == cricket::RELAY_PORT_TYPE) {
44     preference = kPreferenceRelayed;
45   } else {
46     preference = kPreferenceUnknown;
47   }
48   return preference;
49 }
50 
51 // Update the connection address for the MediaContentDescription based on the
52 // candidates.
UpdateConnectionAddress(const JsepCandidateCollection & candidate_collection,cricket::MediaContentDescription * media_desc)53 void UpdateConnectionAddress(
54     const JsepCandidateCollection& candidate_collection,
55     cricket::MediaContentDescription* media_desc) {
56   int port = kDummyPort;
57   std::string ip = kDummyAddress;
58   std::string hostname;
59   int current_preference = kPreferenceUnknown;
60   int current_family = AF_UNSPEC;
61   for (size_t i = 0; i < candidate_collection.count(); ++i) {
62     const IceCandidateInterface* jsep_candidate = candidate_collection.at(i);
63     if (jsep_candidate->candidate().component() !=
64         cricket::ICE_CANDIDATE_COMPONENT_RTP) {
65       continue;
66     }
67     // Default destination should be UDP only.
68     if (jsep_candidate->candidate().protocol() != cricket::UDP_PROTOCOL_NAME) {
69       continue;
70     }
71     const int preference =
72         GetCandidatePreferenceFromType(jsep_candidate->candidate().type());
73     const int family = jsep_candidate->candidate().address().ipaddr().family();
74     // See if this candidate is more preferable then the current one if it's the
75     // same family. Or if the current family is IPv4 already so we could safely
76     // ignore all IPv6 ones. WebRTC bug 4269.
77     // http://code.google.com/p/webrtc/issues/detail?id=4269
78     if ((preference <= current_preference && current_family == family) ||
79         (current_family == AF_INET && family == AF_INET6)) {
80       continue;
81     }
82     current_preference = preference;
83     current_family = family;
84     const rtc::SocketAddress& candidate_addr =
85         jsep_candidate->candidate().address();
86     port = candidate_addr.port();
87     ip = candidate_addr.ipaddr().ToString();
88     hostname = candidate_addr.hostname();
89   }
90   rtc::SocketAddress connection_addr(ip, port);
91   if (rtc::IPIsUnspec(connection_addr.ipaddr()) && !hostname.empty()) {
92     // When a hostname candidate becomes the (default) connection address,
93     // we use the dummy address 0.0.0.0 and port 9 in the c= and the m= lines.
94     //
95     // We have observed in deployment that with a FQDN in a c= line, SDP parsing
96     // could fail in other JSEP implementations. We note that the wildcard
97     // addresses (0.0.0.0 or ::) with port 9 are given the exception as the
98     // connection address that will not result in an ICE mismatch
99     // (draft-ietf-mmusic-ice-sip-sdp). Also, 0.0.0.0 or :: can be used as the
100     // connection address in the initial offer or answer with trickle ICE
101     // if the offerer or answerer does not want to include the host IP address
102     // (draft-ietf-mmusic-trickle-ice-sip), and in particular 0.0.0.0 has been
103     // widely deployed for this use without outstanding compatibility issues.
104     // Combining the above considerations, we use 0.0.0.0 with port 9 to
105     // populate the c= and the m= lines. See |BuildMediaDescription| in
106     // webrtc_sdp.cc for the SDP generation with
107     // |media_desc->connection_address()|.
108     connection_addr = rtc::SocketAddress(kDummyAddress, kDummyPort);
109   }
110   media_desc->set_connection_address(connection_addr);
111 }
112 
113 }  // namespace
114 
115 const int JsepSessionDescription::kDefaultVideoCodecId = 100;
116 const char JsepSessionDescription::kDefaultVideoCodecName[] = "VP8";
117 
118 // TODO(steveanton): Remove this default implementation once Chromium has been
119 // updated.
GetType() const120 SdpType SessionDescriptionInterface::GetType() const {
121   absl::optional<SdpType> maybe_type = SdpTypeFromString(type());
122   if (maybe_type) {
123     return *maybe_type;
124   } else {
125     RTC_LOG(LS_WARNING) << "Default implementation of "
126                            "SessionDescriptionInterface::GetType does not "
127                            "recognize the result from type(), returning "
128                            "kOffer.";
129     return SdpType::kOffer;
130   }
131 }
132 
CreateSessionDescription(const std::string & type,const std::string & sdp,SdpParseError * error)133 SessionDescriptionInterface* CreateSessionDescription(const std::string& type,
134                                                       const std::string& sdp,
135                                                       SdpParseError* error) {
136   absl::optional<SdpType> maybe_type = SdpTypeFromString(type);
137   if (!maybe_type) {
138     return nullptr;
139   }
140 
141   return CreateSessionDescription(*maybe_type, sdp, error).release();
142 }
143 
CreateSessionDescription(SdpType type,const std::string & sdp)144 std::unique_ptr<SessionDescriptionInterface> CreateSessionDescription(
145     SdpType type,
146     const std::string& sdp) {
147   return CreateSessionDescription(type, sdp, nullptr);
148 }
149 
CreateSessionDescription(SdpType type,const std::string & sdp,SdpParseError * error_out)150 std::unique_ptr<SessionDescriptionInterface> CreateSessionDescription(
151     SdpType type,
152     const std::string& sdp,
153     SdpParseError* error_out) {
154   auto jsep_desc = std::make_unique<JsepSessionDescription>(type);
155   if (type != SdpType::kRollback) {
156     if (!SdpDeserialize(sdp, jsep_desc.get(), error_out)) {
157       return nullptr;
158     }
159   }
160   return std::move(jsep_desc);
161 }
162 
CreateSessionDescription(SdpType type,const std::string & session_id,const std::string & session_version,std::unique_ptr<cricket::SessionDescription> description)163 std::unique_ptr<SessionDescriptionInterface> CreateSessionDescription(
164     SdpType type,
165     const std::string& session_id,
166     const std::string& session_version,
167     std::unique_ptr<cricket::SessionDescription> description) {
168   auto jsep_description = std::make_unique<JsepSessionDescription>(type);
169   bool initialize_success = jsep_description->Initialize(
170       std::move(description), session_id, session_version);
171   RTC_DCHECK(initialize_success);
172   return std::move(jsep_description);
173 }
174 
JsepSessionDescription(SdpType type)175 JsepSessionDescription::JsepSessionDescription(SdpType type) : type_(type) {}
176 
JsepSessionDescription(const std::string & type)177 JsepSessionDescription::JsepSessionDescription(const std::string& type) {
178   absl::optional<SdpType> maybe_type = SdpTypeFromString(type);
179   if (maybe_type) {
180     type_ = *maybe_type;
181   } else {
182     RTC_LOG(LS_WARNING)
183         << "JsepSessionDescription constructed with invalid type string: "
184         << type << ". Assuming it is an offer.";
185     type_ = SdpType::kOffer;
186   }
187 }
188 
JsepSessionDescription(SdpType type,std::unique_ptr<cricket::SessionDescription> description,absl::string_view session_id,absl::string_view session_version)189 JsepSessionDescription::JsepSessionDescription(
190     SdpType type,
191     std::unique_ptr<cricket::SessionDescription> description,
192     absl::string_view session_id,
193     absl::string_view session_version)
194     : description_(std::move(description)),
195       session_id_(session_id),
196       session_version_(session_version),
197       type_(type) {
198   RTC_DCHECK(description_);
199   candidate_collection_.resize(number_of_mediasections());
200 }
201 
~JsepSessionDescription()202 JsepSessionDescription::~JsepSessionDescription() {}
203 
Initialize(std::unique_ptr<cricket::SessionDescription> description,const std::string & session_id,const std::string & session_version)204 bool JsepSessionDescription::Initialize(
205     std::unique_ptr<cricket::SessionDescription> description,
206     const std::string& session_id,
207     const std::string& session_version) {
208   if (!description)
209     return false;
210 
211   session_id_ = session_id;
212   session_version_ = session_version;
213   description_ = std::move(description);
214   candidate_collection_.resize(number_of_mediasections());
215   return true;
216 }
217 
Clone() const218 std::unique_ptr<SessionDescriptionInterface> JsepSessionDescription::Clone()
219     const {
220   auto new_description = std::make_unique<JsepSessionDescription>(type_);
221   new_description->session_id_ = session_id_;
222   new_description->session_version_ = session_version_;
223   new_description->description_ = description_->Clone();
224   for (const auto& collection : candidate_collection_) {
225     new_description->candidate_collection_.push_back(collection.Clone());
226   }
227   return new_description;
228 }
229 
AddCandidate(const IceCandidateInterface * candidate)230 bool JsepSessionDescription::AddCandidate(
231     const IceCandidateInterface* candidate) {
232   if (!candidate)
233     return false;
234   size_t mediasection_index = 0;
235   if (!GetMediasectionIndex(candidate, &mediasection_index)) {
236     return false;
237   }
238   if (mediasection_index >= number_of_mediasections())
239     return false;
240   const std::string& content_name =
241       description_->contents()[mediasection_index].name;
242   const cricket::TransportInfo* transport_info =
243       description_->GetTransportInfoByName(content_name);
244   if (!transport_info) {
245     return false;
246   }
247 
248   cricket::Candidate updated_candidate = candidate->candidate();
249   if (updated_candidate.username().empty()) {
250     updated_candidate.set_username(transport_info->description.ice_ufrag);
251   }
252   if (updated_candidate.password().empty()) {
253     updated_candidate.set_password(transport_info->description.ice_pwd);
254   }
255 
256   std::unique_ptr<JsepIceCandidate> updated_candidate_wrapper(
257       new JsepIceCandidate(candidate->sdp_mid(),
258                            static_cast<int>(mediasection_index),
259                            updated_candidate));
260   if (!candidate_collection_[mediasection_index].HasCandidate(
261           updated_candidate_wrapper.get())) {
262     candidate_collection_[mediasection_index].add(
263         updated_candidate_wrapper.release());
264     UpdateConnectionAddress(
265         candidate_collection_[mediasection_index],
266         description_->contents()[mediasection_index].media_description());
267   }
268 
269   return true;
270 }
271 
RemoveCandidates(const std::vector<cricket::Candidate> & candidates)272 size_t JsepSessionDescription::RemoveCandidates(
273     const std::vector<cricket::Candidate>& candidates) {
274   size_t num_removed = 0;
275   for (auto& candidate : candidates) {
276     int mediasection_index = GetMediasectionIndex(candidate);
277     if (mediasection_index < 0) {
278       // Not found.
279       continue;
280     }
281     num_removed += candidate_collection_[mediasection_index].remove(candidate);
282     UpdateConnectionAddress(
283         candidate_collection_[mediasection_index],
284         description_->contents()[mediasection_index].media_description());
285   }
286   return num_removed;
287 }
288 
number_of_mediasections() const289 size_t JsepSessionDescription::number_of_mediasections() const {
290   if (!description_)
291     return 0;
292   return description_->contents().size();
293 }
294 
candidates(size_t mediasection_index) const295 const IceCandidateCollection* JsepSessionDescription::candidates(
296     size_t mediasection_index) const {
297   if (mediasection_index >= candidate_collection_.size())
298     return NULL;
299   return &candidate_collection_[mediasection_index];
300 }
301 
ToString(std::string * out) const302 bool JsepSessionDescription::ToString(std::string* out) const {
303   if (!description_ || !out) {
304     return false;
305   }
306   *out = SdpSerialize(*this);
307   return !out->empty();
308 }
309 
GetMediasectionIndex(const IceCandidateInterface * candidate,size_t * index)310 bool JsepSessionDescription::GetMediasectionIndex(
311     const IceCandidateInterface* candidate,
312     size_t* index) {
313   if (!candidate || !index) {
314     return false;
315   }
316 
317   // If the candidate has no valid mline index or sdp_mid, it is impossible
318   // to find a match.
319   if (candidate->sdp_mid().empty() &&
320       (candidate->sdp_mline_index() < 0 ||
321        static_cast<size_t>(candidate->sdp_mline_index()) >=
322            description_->contents().size())) {
323     return false;
324   }
325 
326   if (candidate->sdp_mline_index() >= 0)
327     *index = static_cast<size_t>(candidate->sdp_mline_index());
328   if (description_ && !candidate->sdp_mid().empty()) {
329     bool found = false;
330     // Try to match the sdp_mid with content name.
331     for (size_t i = 0; i < description_->contents().size(); ++i) {
332       if (candidate->sdp_mid() == description_->contents().at(i).name) {
333         *index = i;
334         found = true;
335         break;
336       }
337     }
338     if (!found) {
339       // If the sdp_mid is presented but we can't find a match, we consider
340       // this as an error.
341       return false;
342     }
343   }
344   return true;
345 }
346 
GetMediasectionIndex(const cricket::Candidate & candidate)347 int JsepSessionDescription::GetMediasectionIndex(
348     const cricket::Candidate& candidate) {
349   // Find the description with a matching transport name of the candidate.
350   const std::string& transport_name = candidate.transport_name();
351   for (size_t i = 0; i < description_->contents().size(); ++i) {
352     if (transport_name == description_->contents().at(i).name) {
353       return static_cast<int>(i);
354     }
355   }
356   return -1;
357 }
358 
359 }  // namespace webrtc
360