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