1 /*
2  *  Copyright 2011 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 "pc/webrtc_sdp.h"
12 
13 #include <ctype.h>
14 #include <limits.h>
15 #include <stdio.h>
16 
17 #include <algorithm>
18 #include <cstdint>
19 #include <map>
20 #include <memory>
21 #include <set>
22 #include <string>
23 #include <unordered_map>
24 #include <utility>
25 #include <vector>
26 
27 #include "absl/algorithm/container.h"
28 #include "api/candidate.h"
29 #include "api/crypto_params.h"
30 #include "api/jsep_ice_candidate.h"
31 #include "api/jsep_session_description.h"
32 #include "api/media_types.h"
33 // for RtpExtension
34 #include "absl/types/optional.h"
35 #include "api/rtc_error.h"
36 #include "api/rtp_parameters.h"
37 #include "api/rtp_transceiver_direction.h"
38 #include "media/base/codec.h"
39 #include "media/base/media_constants.h"
40 #include "media/base/rid_description.h"
41 #include "media/base/rtp_utils.h"
42 #include "media/base/stream_params.h"
43 #include "media/sctp/sctp_transport_internal.h"
44 #include "p2p/base/candidate_pair_interface.h"
45 #include "p2p/base/ice_transport_internal.h"
46 #include "p2p/base/p2p_constants.h"
47 #include "p2p/base/port.h"
48 #include "p2p/base/port_interface.h"
49 #include "p2p/base/transport_description.h"
50 #include "p2p/base/transport_info.h"
51 #include "pc/media_protocol_names.h"
52 #include "pc/media_session.h"
53 #include "pc/sdp_serializer.h"
54 #include "pc/session_description.h"
55 #include "pc/simulcast_description.h"
56 #include "rtc_base/arraysize.h"
57 #include "rtc_base/checks.h"
58 #include "rtc_base/helpers.h"
59 #include "rtc_base/ip_address.h"
60 #include "rtc_base/logging.h"
61 #include "rtc_base/net_helper.h"
62 #include "rtc_base/network_constants.h"
63 #include "rtc_base/socket_address.h"
64 #include "rtc_base/ssl_fingerprint.h"
65 #include "rtc_base/string_encode.h"
66 #include "rtc_base/string_utils.h"
67 #include "rtc_base/strings/string_builder.h"
68 
69 using cricket::AudioContentDescription;
70 using cricket::Candidate;
71 using cricket::Candidates;
72 using cricket::ContentInfo;
73 using cricket::CryptoParams;
74 using cricket::ICE_CANDIDATE_COMPONENT_RTCP;
75 using cricket::ICE_CANDIDATE_COMPONENT_RTP;
76 using cricket::kApplicationSpecificBandwidth;
77 using cricket::kCodecParamMaxPTime;
78 using cricket::kCodecParamMinPTime;
79 using cricket::kCodecParamPTime;
80 using cricket::kTransportSpecificBandwidth;
81 using cricket::MediaContentDescription;
82 using cricket::MediaProtocolType;
83 using cricket::MediaType;
84 using cricket::RidDescription;
85 using cricket::RtpDataContentDescription;
86 using cricket::RtpHeaderExtensions;
87 using cricket::SctpDataContentDescription;
88 using cricket::SimulcastDescription;
89 using cricket::SimulcastLayer;
90 using cricket::SimulcastLayerList;
91 using cricket::SsrcGroup;
92 using cricket::StreamParams;
93 using cricket::StreamParamsVec;
94 using cricket::TransportDescription;
95 using cricket::TransportInfo;
96 using cricket::UnsupportedContentDescription;
97 using cricket::VideoContentDescription;
98 using rtc::SocketAddress;
99 
100 // TODO(deadbeef): Switch to using anonymous namespace rather than declaring
101 // everything "static".
102 namespace webrtc {
103 
104 // Line type
105 // RFC 4566
106 // An SDP session description consists of a number of lines of text of
107 // the form:
108 // <type>=<value>
109 // where <type> MUST be exactly one case-significant character.
110 
111 // Legal characters in a <token> value (RFC 4566 section 9):
112 //    token-char =          %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39
113 //                         / %x41-5A / %x5E-7E
114 static const char kLegalTokenCharacters[] =
115     "!#$%&'*+-."                          // %x21, %x23-27, %x2A-2B, %x2D-2E
116     "0123456789"                          // %x30-39
117     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"          // %x41-5A
118     "^_`abcdefghijklmnopqrstuvwxyz{|}~";  // %x5E-7E
119 static const int kLinePrefixLength = 2;  // Length of <type>=
120 static const char kLineTypeVersion = 'v';
121 static const char kLineTypeOrigin = 'o';
122 static const char kLineTypeSessionName = 's';
123 static const char kLineTypeSessionInfo = 'i';
124 static const char kLineTypeSessionUri = 'u';
125 static const char kLineTypeSessionEmail = 'e';
126 static const char kLineTypeSessionPhone = 'p';
127 static const char kLineTypeSessionBandwidth = 'b';
128 static const char kLineTypeTiming = 't';
129 static const char kLineTypeRepeatTimes = 'r';
130 static const char kLineTypeTimeZone = 'z';
131 static const char kLineTypeEncryptionKey = 'k';
132 static const char kLineTypeMedia = 'm';
133 static const char kLineTypeConnection = 'c';
134 static const char kLineTypeAttributes = 'a';
135 
136 // Attributes
137 static const char kAttributeGroup[] = "group";
138 static const char kAttributeMid[] = "mid";
139 static const char kAttributeMsid[] = "msid";
140 static const char kAttributeBundleOnly[] = "bundle-only";
141 static const char kAttributeRtcpMux[] = "rtcp-mux";
142 static const char kAttributeRtcpReducedSize[] = "rtcp-rsize";
143 static const char kAttributeSsrc[] = "ssrc";
144 static const char kSsrcAttributeCname[] = "cname";
145 static const char kAttributeExtmapAllowMixed[] = "extmap-allow-mixed";
146 static const char kAttributeExtmap[] = "extmap";
147 // draft-alvestrand-mmusic-msid-01
148 // a=msid-semantic: WMS
149 // This is a legacy field supported only for Plan B semantics.
150 static const char kAttributeMsidSemantics[] = "msid-semantic";
151 static const char kMediaStreamSemantic[] = "WMS";
152 static const char kSsrcAttributeMsid[] = "msid";
153 static const char kDefaultMsid[] = "default";
154 static const char kNoStreamMsid[] = "-";
155 static const char kSsrcAttributeMslabel[] = "mslabel";
156 static const char kSSrcAttributeLabel[] = "label";
157 static const char kAttributeSsrcGroup[] = "ssrc-group";
158 static const char kAttributeCrypto[] = "crypto";
159 static const char kAttributeCandidate[] = "candidate";
160 static const char kAttributeCandidateTyp[] = "typ";
161 static const char kAttributeCandidateRaddr[] = "raddr";
162 static const char kAttributeCandidateRport[] = "rport";
163 static const char kAttributeCandidateUfrag[] = "ufrag";
164 static const char kAttributeCandidatePwd[] = "pwd";
165 static const char kAttributeCandidateGeneration[] = "generation";
166 static const char kAttributeCandidateNetworkId[] = "network-id";
167 static const char kAttributeCandidateNetworkCost[] = "network-cost";
168 static const char kAttributeFingerprint[] = "fingerprint";
169 static const char kAttributeSetup[] = "setup";
170 static const char kAttributeFmtp[] = "fmtp";
171 static const char kAttributeRtpmap[] = "rtpmap";
172 static const char kAttributeSctpmap[] = "sctpmap";
173 static const char kAttributeRtcp[] = "rtcp";
174 static const char kAttributeIceUfrag[] = "ice-ufrag";
175 static const char kAttributeIcePwd[] = "ice-pwd";
176 static const char kAttributeIceLite[] = "ice-lite";
177 static const char kAttributeIceOption[] = "ice-options";
178 static const char kAttributeSendOnly[] = "sendonly";
179 static const char kAttributeRecvOnly[] = "recvonly";
180 static const char kAttributeRtcpFb[] = "rtcp-fb";
181 static const char kAttributeSendRecv[] = "sendrecv";
182 static const char kAttributeInactive[] = "inactive";
183 // draft-ietf-mmusic-sctp-sdp-26
184 // a=sctp-port, a=max-message-size
185 static const char kAttributeSctpPort[] = "sctp-port";
186 static const char kAttributeMaxMessageSize[] = "max-message-size";
187 static const int kDefaultSctpMaxMessageSize = 65536;
188 // draft-ietf-mmusic-sdp-simulcast-13
189 // a=simulcast
190 static const char kAttributeSimulcast[] = "simulcast";
191 // draft-ietf-mmusic-rid-15
192 // a=rid
193 static const char kAttributeRid[] = "rid";
194 static const char kAttributePacketization[] = "packetization";
195 
196 // Experimental flags
197 static const char kAttributeXGoogleFlag[] = "x-google-flag";
198 static const char kValueConference[] = "conference";
199 
200 static const char kAttributeRtcpRemoteEstimate[] = "remote-net-estimate";
201 
202 // Candidate
203 static const char kCandidateHost[] = "host";
204 static const char kCandidateSrflx[] = "srflx";
205 static const char kCandidatePrflx[] = "prflx";
206 static const char kCandidateRelay[] = "relay";
207 static const char kTcpCandidateType[] = "tcptype";
208 
209 // rtc::StringBuilder doesn't have a << overload for chars, while rtc::split and
210 // rtc::tokenize_first both take a char delimiter. To handle both cases these
211 // constants come in pairs of a chars and length-one strings.
212 static const char kSdpDelimiterEqual[] = "=";
213 static const char kSdpDelimiterEqualChar = '=';
214 static const char kSdpDelimiterSpace[] = " ";
215 static const char kSdpDelimiterSpaceChar = ' ';
216 static const char kSdpDelimiterColon[] = ":";
217 static const char kSdpDelimiterColonChar = ':';
218 static const char kSdpDelimiterSemicolon[] = ";";
219 static const char kSdpDelimiterSemicolonChar = ';';
220 static const char kSdpDelimiterSlashChar = '/';
221 static const char kNewLine[] = "\n";
222 static const char kNewLineChar = '\n';
223 static const char kReturnChar = '\r';
224 static const char kLineBreak[] = "\r\n";
225 
226 // TODO(deadbeef): Generate the Session and Time description
227 // instead of hardcoding.
228 static const char kSessionVersion[] = "v=0";
229 // RFC 4566
230 static const char kSessionOriginUsername[] = "-";
231 static const char kSessionOriginSessionId[] = "0";
232 static const char kSessionOriginSessionVersion[] = "0";
233 static const char kSessionOriginNettype[] = "IN";
234 static const char kSessionOriginAddrtype[] = "IP4";
235 static const char kSessionOriginAddress[] = "127.0.0.1";
236 static const char kSessionName[] = "s=-";
237 static const char kTimeDescription[] = "t=0 0";
238 static const char kAttrGroup[] = "a=group:BUNDLE";
239 static const char kConnectionNettype[] = "IN";
240 static const char kConnectionIpv4Addrtype[] = "IP4";
241 static const char kConnectionIpv6Addrtype[] = "IP6";
242 static const char kMediaTypeVideo[] = "video";
243 static const char kMediaTypeAudio[] = "audio";
244 static const char kMediaTypeData[] = "application";
245 static const char kMediaPortRejected[] = "0";
246 // draft-ietf-mmusic-trickle-ice-01
247 // When no candidates have been gathered, set the connection
248 // address to IP6 ::.
249 // TODO(perkj): FF can not parse IP6 ::. See http://crbug/430333
250 // Use IPV4 per default.
251 static const char kDummyAddress[] = "0.0.0.0";
252 static const char kDummyPort[] = "9";
253 
254 static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel";
255 
256 // RTP payload type is in the 0-127 range. Use -1 to indicate "all" payload
257 // types.
258 const int kWildcardPayloadType = -1;
259 
260 struct SsrcInfo {
261   uint32_t ssrc_id;
262   std::string cname;
263   std::string stream_id;
264   std::string track_id;
265 
266   // For backward compatibility.
267   // TODO(ronghuawu): Remove below 2 fields once all the clients support msid.
268   std::string label;
269   std::string mslabel;
270 };
271 typedef std::vector<SsrcInfo> SsrcInfoVec;
272 typedef std::vector<SsrcGroup> SsrcGroupVec;
273 
274 template <class T>
275 static void AddFmtpLine(const T& codec, std::string* message);
276 static void BuildMediaDescription(const ContentInfo* content_info,
277                                   const TransportInfo* transport_info,
278                                   const cricket::MediaType media_type,
279                                   const std::vector<Candidate>& candidates,
280                                   int msid_signaling,
281                                   std::string* message);
282 static void BuildRtpContentAttributes(const MediaContentDescription* media_desc,
283                                       const cricket::MediaType media_type,
284                                       int msid_signaling,
285                                       std::string* message);
286 static void BuildRtpMap(const MediaContentDescription* media_desc,
287                         const cricket::MediaType media_type,
288                         std::string* message);
289 static void BuildCandidate(const std::vector<Candidate>& candidates,
290                            bool include_ufrag,
291                            std::string* message);
292 static void BuildIceOptions(const std::vector<std::string>& transport_options,
293                             std::string* message);
294 static bool ParseSessionDescription(const std::string& message,
295                                     size_t* pos,
296                                     std::string* session_id,
297                                     std::string* session_version,
298                                     TransportDescription* session_td,
299                                     RtpHeaderExtensions* session_extmaps,
300                                     rtc::SocketAddress* connection_addr,
301                                     cricket::SessionDescription* desc,
302                                     SdpParseError* error);
303 static bool ParseMediaDescription(
304     const std::string& message,
305     const TransportDescription& session_td,
306     const RtpHeaderExtensions& session_extmaps,
307     size_t* pos,
308     const rtc::SocketAddress& session_connection_addr,
309     cricket::SessionDescription* desc,
310     std::vector<std::unique_ptr<JsepIceCandidate>>* candidates,
311     SdpParseError* error);
312 static bool ParseContent(
313     const std::string& message,
314     const cricket::MediaType media_type,
315     int mline_index,
316     const std::string& protocol,
317     const std::vector<int>& payload_types,
318     size_t* pos,
319     std::string* content_name,
320     bool* bundle_only,
321     int* msid_signaling,
322     MediaContentDescription* media_desc,
323     TransportDescription* transport,
324     std::vector<std::unique_ptr<JsepIceCandidate>>* candidates,
325     SdpParseError* error);
326 static bool ParseGroupAttribute(const std::string& line,
327                                 cricket::SessionDescription* desc,
328                                 SdpParseError* error);
329 static bool ParseSsrcAttribute(const std::string& line,
330                                SsrcInfoVec* ssrc_infos,
331                                int* msid_signaling,
332                                SdpParseError* error);
333 static bool ParseSsrcGroupAttribute(const std::string& line,
334                                     SsrcGroupVec* ssrc_groups,
335                                     SdpParseError* error);
336 static bool ParseCryptoAttribute(const std::string& line,
337                                  MediaContentDescription* media_desc,
338                                  SdpParseError* error);
339 static bool ParseRtpmapAttribute(const std::string& line,
340                                  const cricket::MediaType media_type,
341                                  const std::vector<int>& payload_types,
342                                  MediaContentDescription* media_desc,
343                                  SdpParseError* error);
344 static bool ParseFmtpAttributes(const std::string& line,
345                                 const cricket::MediaType media_type,
346                                 MediaContentDescription* media_desc,
347                                 SdpParseError* error);
348 static bool ParseFmtpParam(const std::string& line,
349                            std::string* parameter,
350                            std::string* value,
351                            SdpParseError* error);
352 static bool ParsePacketizationAttribute(const std::string& line,
353                                         const cricket::MediaType media_type,
354                                         MediaContentDescription* media_desc,
355                                         SdpParseError* error);
356 static bool ParseRtcpFbAttribute(const std::string& line,
357                                  const cricket::MediaType media_type,
358                                  MediaContentDescription* media_desc,
359                                  SdpParseError* error);
360 static bool ParseIceOptions(const std::string& line,
361                             std::vector<std::string>* transport_options,
362                             SdpParseError* error);
363 static bool ParseExtmap(const std::string& line,
364                         RtpExtension* extmap,
365                         SdpParseError* error);
366 static bool ParseFingerprintAttribute(
367     const std::string& line,
368     std::unique_ptr<rtc::SSLFingerprint>* fingerprint,
369     SdpParseError* error);
370 static bool ParseDtlsSetup(const std::string& line,
371                            cricket::ConnectionRole* role,
372                            SdpParseError* error);
373 static bool ParseMsidAttribute(const std::string& line,
374                                std::vector<std::string>* stream_ids,
375                                std::string* track_id,
376                                SdpParseError* error);
377 
378 static void RemoveInvalidRidDescriptions(const std::vector<int>& payload_types,
379                                          std::vector<RidDescription>* rids);
380 
381 static SimulcastLayerList RemoveRidsFromSimulcastLayerList(
382     const std::set<std::string>& to_remove,
383     const SimulcastLayerList& layers);
384 
385 static void RemoveInvalidRidsFromSimulcast(
386     const std::vector<RidDescription>& rids,
387     SimulcastDescription* simulcast);
388 
389 // Helper functions
390 
391 // Below ParseFailed*** functions output the line that caused the parsing
392 // failure and the detailed reason (|description|) of the failure to |error|.
393 // The functions always return false so that they can be used directly in the
394 // following way when error happens:
395 // "return ParseFailed***(...);"
396 
397 // The line starting at |line_start| of |message| is the failing line.
398 // The reason for the failure should be provided in the |description|.
399 // An example of a description could be "unknown character".
ParseFailed(const std::string & message,size_t line_start,const std::string & description,SdpParseError * error)400 static bool ParseFailed(const std::string& message,
401                         size_t line_start,
402                         const std::string& description,
403                         SdpParseError* error) {
404   // Get the first line of |message| from |line_start|.
405   std::string first_line;
406   size_t line_end = message.find(kNewLine, line_start);
407   if (line_end != std::string::npos) {
408     if (line_end > 0 && (message.at(line_end - 1) == kReturnChar)) {
409       --line_end;
410     }
411     first_line = message.substr(line_start, (line_end - line_start));
412   } else {
413     first_line = message.substr(line_start);
414   }
415 
416   if (error) {
417     error->line = first_line;
418     error->description = description;
419   }
420   RTC_LOG(LS_ERROR) << "Failed to parse: \"" << first_line
421                     << "\". Reason: " << description;
422   return false;
423 }
424 
425 // |line| is the failing line. The reason for the failure should be
426 // provided in the |description|.
ParseFailed(const std::string & line,const std::string & description,SdpParseError * error)427 static bool ParseFailed(const std::string& line,
428                         const std::string& description,
429                         SdpParseError* error) {
430   return ParseFailed(line, 0, description, error);
431 }
432 
433 // Parses failure where the failing SDP line isn't know or there are multiple
434 // failing lines.
ParseFailed(const std::string & description,SdpParseError * error)435 static bool ParseFailed(const std::string& description, SdpParseError* error) {
436   return ParseFailed("", description, error);
437 }
438 
439 // |line| is the failing line. The failure is due to the fact that |line|
440 // doesn't have |expected_fields| fields.
ParseFailedExpectFieldNum(const std::string & line,int expected_fields,SdpParseError * error)441 static bool ParseFailedExpectFieldNum(const std::string& line,
442                                       int expected_fields,
443                                       SdpParseError* error) {
444   rtc::StringBuilder description;
445   description << "Expects " << expected_fields << " fields.";
446   return ParseFailed(line, description.str(), error);
447 }
448 
449 // |line| is the failing line. The failure is due to the fact that |line| has
450 // less than |expected_min_fields| fields.
ParseFailedExpectMinFieldNum(const std::string & line,int expected_min_fields,SdpParseError * error)451 static bool ParseFailedExpectMinFieldNum(const std::string& line,
452                                          int expected_min_fields,
453                                          SdpParseError* error) {
454   rtc::StringBuilder description;
455   description << "Expects at least " << expected_min_fields << " fields.";
456   return ParseFailed(line, description.str(), error);
457 }
458 
459 // |line| is the failing line. The failure is due to the fact that it failed to
460 // get the value of |attribute|.
ParseFailedGetValue(const std::string & line,const std::string & attribute,SdpParseError * error)461 static bool ParseFailedGetValue(const std::string& line,
462                                 const std::string& attribute,
463                                 SdpParseError* error) {
464   rtc::StringBuilder description;
465   description << "Failed to get the value of attribute: " << attribute;
466   return ParseFailed(line, description.str(), error);
467 }
468 
469 // The line starting at |line_start| of |message| is the failing line. The
470 // failure is due to the line type (e.g. the "m" part of the "m-line")
471 // not matching what is expected. The expected line type should be
472 // provided as |line_type|.
ParseFailedExpectLine(const std::string & message,size_t line_start,const char line_type,const std::string & line_value,SdpParseError * error)473 static bool ParseFailedExpectLine(const std::string& message,
474                                   size_t line_start,
475                                   const char line_type,
476                                   const std::string& line_value,
477                                   SdpParseError* error) {
478   rtc::StringBuilder description;
479   description << "Expect line: " << std::string(1, line_type) << "="
480               << line_value;
481   return ParseFailed(message, line_start, description.str(), error);
482 }
483 
AddLine(const std::string & line,std::string * message)484 static bool AddLine(const std::string& line, std::string* message) {
485   if (!message)
486     return false;
487 
488   message->append(line);
489   message->append(kLineBreak);
490   return true;
491 }
492 
GetLine(const std::string & message,size_t * pos,std::string * line)493 static bool GetLine(const std::string& message,
494                     size_t* pos,
495                     std::string* line) {
496   size_t line_begin = *pos;
497   size_t line_end = message.find(kNewLine, line_begin);
498   if (line_end == std::string::npos) {
499     return false;
500   }
501   // Update the new start position
502   *pos = line_end + 1;
503   if (line_end > 0 && (message.at(line_end - 1) == kReturnChar)) {
504     --line_end;
505   }
506   *line = message.substr(line_begin, (line_end - line_begin));
507   const char* cline = line->c_str();
508   // RFC 4566
509   // An SDP session description consists of a number of lines of text of
510   // the form:
511   // <type>=<value>
512   // where <type> MUST be exactly one case-significant character and
513   // <value> is structured text whose format depends on <type>.
514   // Whitespace MUST NOT be used on either side of the "=" sign.
515   //
516   // However, an exception to the whitespace rule is made for "s=", since
517   // RFC4566 also says:
518   //
519   //   If a session has no meaningful name, the value "s= " SHOULD be used
520   //   (i.e., a single space as the session name).
521   if (line->length() < 3 || !islower(cline[0]) ||
522       cline[1] != kSdpDelimiterEqualChar ||
523       (cline[0] != kLineTypeSessionName &&
524        cline[2] == kSdpDelimiterSpaceChar)) {
525     *pos = line_begin;
526     return false;
527   }
528   return true;
529 }
530 
531 // Init |os| to "|type|=|value|".
InitLine(const char type,const std::string & value,rtc::StringBuilder * os)532 static void InitLine(const char type,
533                      const std::string& value,
534                      rtc::StringBuilder* os) {
535   os->Clear();
536   *os << std::string(1, type) << kSdpDelimiterEqual << value;
537 }
538 
539 // Init |os| to "a=|attribute|".
InitAttrLine(const std::string & attribute,rtc::StringBuilder * os)540 static void InitAttrLine(const std::string& attribute, rtc::StringBuilder* os) {
541   InitLine(kLineTypeAttributes, attribute, os);
542 }
543 
544 // Writes a SDP attribute line based on |attribute| and |value| to |message|.
AddAttributeLine(const std::string & attribute,int value,std::string * message)545 static void AddAttributeLine(const std::string& attribute,
546                              int value,
547                              std::string* message) {
548   rtc::StringBuilder os;
549   InitAttrLine(attribute, &os);
550   os << kSdpDelimiterColon << value;
551   AddLine(os.str(), message);
552 }
553 
IsLineType(const std::string & message,const char type,size_t line_start)554 static bool IsLineType(const std::string& message,
555                        const char type,
556                        size_t line_start) {
557   if (message.size() < line_start + kLinePrefixLength) {
558     return false;
559   }
560   const char* cmessage = message.c_str();
561   return (cmessage[line_start] == type &&
562           cmessage[line_start + 1] == kSdpDelimiterEqualChar);
563 }
564 
IsLineType(const std::string & line,const char type)565 static bool IsLineType(const std::string& line, const char type) {
566   return IsLineType(line, type, 0);
567 }
568 
GetLineWithType(const std::string & message,size_t * pos,std::string * line,const char type)569 static bool GetLineWithType(const std::string& message,
570                             size_t* pos,
571                             std::string* line,
572                             const char type) {
573   if (!IsLineType(message, type, *pos)) {
574     return false;
575   }
576 
577   if (!GetLine(message, pos, line))
578     return false;
579 
580   return true;
581 }
582 
HasAttribute(const std::string & line,const std::string & attribute)583 static bool HasAttribute(const std::string& line,
584                          const std::string& attribute) {
585   if (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0) {
586     // Make sure that the match is not only a partial match. If length of
587     // strings doesn't match, the next character of the line must be ':' or ' '.
588     // This function is also used for media descriptions (e.g., "m=audio 9..."),
589     // hence the need to also allow space in the end.
590     RTC_CHECK_LE(kLinePrefixLength + attribute.size(), line.size());
591     if ((kLinePrefixLength + attribute.size()) == line.size() ||
592         line[kLinePrefixLength + attribute.size()] == kSdpDelimiterColonChar ||
593         line[kLinePrefixLength + attribute.size()] == kSdpDelimiterSpaceChar) {
594       return true;
595     }
596   }
597   return false;
598 }
599 
AddSsrcLine(uint32_t ssrc_id,const std::string & attribute,const std::string & value,std::string * message)600 static bool AddSsrcLine(uint32_t ssrc_id,
601                         const std::string& attribute,
602                         const std::string& value,
603                         std::string* message) {
604   // RFC 5576
605   // a=ssrc:<ssrc-id> <attribute>:<value>
606   rtc::StringBuilder os;
607   InitAttrLine(kAttributeSsrc, &os);
608   os << kSdpDelimiterColon << ssrc_id << kSdpDelimiterSpace << attribute
609      << kSdpDelimiterColon << value;
610   return AddLine(os.str(), message);
611 }
612 
613 // Get value only from <attribute>:<value>.
GetValue(const std::string & message,const std::string & attribute,std::string * value,SdpParseError * error)614 static bool GetValue(const std::string& message,
615                      const std::string& attribute,
616                      std::string* value,
617                      SdpParseError* error) {
618   std::string leftpart;
619   if (!rtc::tokenize_first(message, kSdpDelimiterColonChar, &leftpart, value)) {
620     return ParseFailedGetValue(message, attribute, error);
621   }
622   // The left part should end with the expected attribute.
623   if (leftpart.length() < attribute.length() ||
624       leftpart.compare(leftpart.length() - attribute.length(),
625                        attribute.length(), attribute) != 0) {
626     return ParseFailedGetValue(message, attribute, error);
627   }
628   return true;
629 }
630 
631 // Get a single [token] from <attribute>:<token>
GetSingleTokenValue(const std::string & message,const std::string & attribute,std::string * value,SdpParseError * error)632 static bool GetSingleTokenValue(const std::string& message,
633                                 const std::string& attribute,
634                                 std::string* value,
635                                 SdpParseError* error) {
636   if (!GetValue(message, attribute, value, error)) {
637     return false;
638   }
639   if (strspn(value->c_str(), kLegalTokenCharacters) != value->size()) {
640     rtc::StringBuilder description;
641     description << "Illegal character found in the value of " << attribute;
642     return ParseFailed(message, description.str(), error);
643   }
644   return true;
645 }
646 
CaseInsensitiveFind(std::string str1,std::string str2)647 static bool CaseInsensitiveFind(std::string str1, std::string str2) {
648   absl::c_transform(str1, str1.begin(), ::tolower);
649   absl::c_transform(str2, str2.begin(), ::tolower);
650   return str1.find(str2) != std::string::npos;
651 }
652 
653 template <class T>
GetValueFromString(const std::string & line,const std::string & s,T * t,SdpParseError * error)654 static bool GetValueFromString(const std::string& line,
655                                const std::string& s,
656                                T* t,
657                                SdpParseError* error) {
658   if (!rtc::FromString(s, t)) {
659     rtc::StringBuilder description;
660     description << "Invalid value: " << s << ".";
661     return ParseFailed(line, description.str(), error);
662   }
663   return true;
664 }
665 
GetPayloadTypeFromString(const std::string & line,const std::string & s,int * payload_type,SdpParseError * error)666 static bool GetPayloadTypeFromString(const std::string& line,
667                                      const std::string& s,
668                                      int* payload_type,
669                                      SdpParseError* error) {
670   return GetValueFromString(line, s, payload_type, error) &&
671          cricket::IsValidRtpPayloadType(*payload_type);
672 }
673 
674 // Creates a StreamParams track in the case when no SSRC lines are signaled.
675 // This is a track that does not contain SSRCs and only contains
676 // stream_ids/track_id if it's signaled with a=msid lines.
CreateTrackWithNoSsrcs(const std::vector<std::string> & msid_stream_ids,const std::string & msid_track_id,const std::vector<RidDescription> & rids,StreamParamsVec * tracks)677 void CreateTrackWithNoSsrcs(const std::vector<std::string>& msid_stream_ids,
678                             const std::string& msid_track_id,
679                             const std::vector<RidDescription>& rids,
680                             StreamParamsVec* tracks) {
681   StreamParams track;
682   if (msid_track_id.empty() && rids.empty()) {
683     // We only create an unsignaled track if a=msid lines were signaled.
684     RTC_LOG(LS_INFO) << "MSID not signaled, skipping creation of StreamParams";
685     return;
686   }
687   track.set_stream_ids(msid_stream_ids);
688   track.id = msid_track_id;
689   track.set_rids(rids);
690   tracks->push_back(track);
691 }
692 
693 // Creates the StreamParams tracks, for the case when SSRC lines are signaled.
694 // |msid_stream_ids| and |msid_track_id| represent the stream/track ID from the
695 // "a=msid" attribute, if it exists. They are empty if the attribute does not
696 // exist. We prioritize getting stream_ids/track_ids signaled in a=msid lines.
CreateTracksFromSsrcInfos(const SsrcInfoVec & ssrc_infos,const std::vector<std::string> & msid_stream_ids,const std::string & msid_track_id,StreamParamsVec * tracks,int msid_signaling)697 void CreateTracksFromSsrcInfos(const SsrcInfoVec& ssrc_infos,
698                                const std::vector<std::string>& msid_stream_ids,
699                                const std::string& msid_track_id,
700                                StreamParamsVec* tracks,
701                                int msid_signaling) {
702   RTC_DCHECK(tracks != NULL);
703   for (const SsrcInfo& ssrc_info : ssrc_infos) {
704     // According to https://tools.ietf.org/html/rfc5576#section-6.1, the CNAME
705     // attribute is mandatory, but we relax that restriction.
706     if (ssrc_info.cname.empty()) {
707       RTC_LOG(LS_WARNING) << "CNAME attribute missing for SSRC "
708                           << ssrc_info.ssrc_id;
709     }
710     std::vector<std::string> stream_ids;
711     std::string track_id;
712     if (msid_signaling & cricket::kMsidSignalingMediaSection) {
713       // This is the case with Unified Plan SDP msid signaling.
714       stream_ids = msid_stream_ids;
715       track_id = msid_track_id;
716     } else if (msid_signaling & cricket::kMsidSignalingSsrcAttribute) {
717       // This is the case with Plan B SDP msid signaling.
718       stream_ids.push_back(ssrc_info.stream_id);
719       track_id = ssrc_info.track_id;
720     } else if (!ssrc_info.mslabel.empty()) {
721       // Since there's no a=msid or a=ssrc msid signaling, this is a sdp from
722       // an older version of client that doesn't support msid.
723       // In that case, we use the mslabel and label to construct the track.
724       stream_ids.push_back(ssrc_info.mslabel);
725       track_id = ssrc_info.label;
726     } else {
727       // Since no media streams isn't supported with older SDP signaling, we
728       // use a default a stream id.
729       stream_ids.push_back(kDefaultMsid);
730     }
731     // If a track ID wasn't populated from the SSRC attributes OR the
732     // msid attribute, use default/random values.
733     if (track_id.empty()) {
734       // TODO(ronghuawu): What should we do if the track id doesn't appear?
735       // Create random string (which will be used as track label later)?
736       track_id = rtc::CreateRandomString(8);
737     }
738 
739     auto track_it = absl::c_find_if(
740         *tracks,
741         [track_id](const StreamParams& track) { return track.id == track_id; });
742     if (track_it == tracks->end()) {
743       // If we don't find an existing track, create a new one.
744       tracks->push_back(StreamParams());
745       track_it = tracks->end() - 1;
746     }
747     StreamParams& track = *track_it;
748     track.add_ssrc(ssrc_info.ssrc_id);
749     track.cname = ssrc_info.cname;
750     track.set_stream_ids(stream_ids);
751     track.id = track_id;
752   }
753 }
754 
GetMediaStreamIds(const ContentInfo * content,std::set<std::string> * labels)755 void GetMediaStreamIds(const ContentInfo* content,
756                        std::set<std::string>* labels) {
757   for (const StreamParams& stream_params :
758        content->media_description()->streams()) {
759     for (const std::string& stream_id : stream_params.stream_ids()) {
760       labels->insert(stream_id);
761     }
762   }
763 }
764 
765 // RFC 5245
766 // It is RECOMMENDED that default candidates be chosen based on the
767 // likelihood of those candidates to work with the peer that is being
768 // contacted.  It is RECOMMENDED that relayed > reflexive > host.
769 static const int kPreferenceUnknown = 0;
770 static const int kPreferenceHost = 1;
771 static const int kPreferenceReflexive = 2;
772 static const int kPreferenceRelayed = 3;
773 
GetCandidatePreferenceFromType(const std::string & type)774 static int GetCandidatePreferenceFromType(const std::string& type) {
775   int preference = kPreferenceUnknown;
776   if (type == cricket::LOCAL_PORT_TYPE) {
777     preference = kPreferenceHost;
778   } else if (type == cricket::STUN_PORT_TYPE) {
779     preference = kPreferenceReflexive;
780   } else if (type == cricket::RELAY_PORT_TYPE) {
781     preference = kPreferenceRelayed;
782   } else {
783     RTC_NOTREACHED();
784   }
785   return preference;
786 }
787 
788 // Get ip and port of the default destination from the |candidates| with the
789 // given value of |component_id|. The default candidate should be the one most
790 // likely to work, typically IPv4 relay.
791 // RFC 5245
792 // The value of |component_id| currently supported are 1 (RTP) and 2 (RTCP).
793 // TODO(deadbeef): Decide the default destination in webrtcsession and
794 // pass it down via SessionDescription.
GetDefaultDestination(const std::vector<Candidate> & candidates,int component_id,std::string * port,std::string * ip,std::string * addr_type)795 static void GetDefaultDestination(const std::vector<Candidate>& candidates,
796                                   int component_id,
797                                   std::string* port,
798                                   std::string* ip,
799                                   std::string* addr_type) {
800   *addr_type = kConnectionIpv4Addrtype;
801   *port = kDummyPort;
802   *ip = kDummyAddress;
803   int current_preference = kPreferenceUnknown;
804   int current_family = AF_UNSPEC;
805   for (const Candidate& candidate : candidates) {
806     if (candidate.component() != component_id) {
807       continue;
808     }
809     // Default destination should be UDP only.
810     if (candidate.protocol() != cricket::UDP_PROTOCOL_NAME) {
811       continue;
812     }
813     const int preference = GetCandidatePreferenceFromType(candidate.type());
814     const int family = candidate.address().ipaddr().family();
815     // See if this candidate is more preferable then the current one if it's the
816     // same family. Or if the current family is IPv4 already so we could safely
817     // ignore all IPv6 ones. WebRTC bug 4269.
818     // http://code.google.com/p/webrtc/issues/detail?id=4269
819     if ((preference <= current_preference && current_family == family) ||
820         (current_family == AF_INET && family == AF_INET6)) {
821       continue;
822     }
823     if (family == AF_INET) {
824       addr_type->assign(kConnectionIpv4Addrtype);
825     } else if (family == AF_INET6) {
826       addr_type->assign(kConnectionIpv6Addrtype);
827     }
828     current_preference = preference;
829     current_family = family;
830     *port = candidate.address().PortAsString();
831     *ip = candidate.address().ipaddr().ToString();
832   }
833 }
834 
835 // Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
GetRtcpLine(const std::vector<Candidate> & candidates)836 static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
837   std::string rtcp_line, rtcp_port, rtcp_ip, addr_type;
838   GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP, &rtcp_port,
839                         &rtcp_ip, &addr_type);
840   // Found default RTCP candidate.
841   // RFC 5245
842   // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
843   // using the a=rtcp attribute as defined in RFC 3605.
844 
845   // RFC 3605
846   // rtcp-attribute =  "a=rtcp:" port  [nettype space addrtype space
847   // connection-address] CRLF
848   rtc::StringBuilder os;
849   InitAttrLine(kAttributeRtcp, &os);
850   os << kSdpDelimiterColon << rtcp_port << " " << kConnectionNettype << " "
851      << addr_type << " " << rtcp_ip;
852   rtcp_line = os.str();
853   return rtcp_line;
854 }
855 
856 // Get candidates according to the mline index from SessionDescriptionInterface.
GetCandidatesByMindex(const SessionDescriptionInterface & desci,int mline_index,std::vector<Candidate> * candidates)857 static void GetCandidatesByMindex(const SessionDescriptionInterface& desci,
858                                   int mline_index,
859                                   std::vector<Candidate>* candidates) {
860   if (!candidates) {
861     return;
862   }
863   const IceCandidateCollection* cc = desci.candidates(mline_index);
864   for (size_t i = 0; i < cc->count(); ++i) {
865     const IceCandidateInterface* candidate = cc->at(i);
866     candidates->push_back(candidate->candidate());
867   }
868 }
869 
IsValidPort(int port)870 static bool IsValidPort(int port) {
871   return port >= 0 && port <= 65535;
872 }
873 
SdpSerialize(const JsepSessionDescription & jdesc)874 std::string SdpSerialize(const JsepSessionDescription& jdesc) {
875   const cricket::SessionDescription* desc = jdesc.description();
876   if (!desc) {
877     return "";
878   }
879 
880   std::string message;
881 
882   // Session Description.
883   AddLine(kSessionVersion, &message);
884   // Session Origin
885   // RFC 4566
886   // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
887   // <unicast-address>
888   rtc::StringBuilder os;
889   InitLine(kLineTypeOrigin, kSessionOriginUsername, &os);
890   const std::string& session_id =
891       jdesc.session_id().empty() ? kSessionOriginSessionId : jdesc.session_id();
892   const std::string& session_version = jdesc.session_version().empty()
893                                            ? kSessionOriginSessionVersion
894                                            : jdesc.session_version();
895   os << " " << session_id << " " << session_version << " "
896      << kSessionOriginNettype << " " << kSessionOriginAddrtype << " "
897      << kSessionOriginAddress;
898   AddLine(os.str(), &message);
899   AddLine(kSessionName, &message);
900 
901   // Time Description.
902   AddLine(kTimeDescription, &message);
903 
904   // Group
905   if (desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
906     std::string group_line = kAttrGroup;
907     const cricket::ContentGroup* group =
908         desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
909     RTC_DCHECK(group != NULL);
910     for (const std::string& content_name : group->content_names()) {
911       group_line.append(" ");
912       group_line.append(content_name);
913     }
914     AddLine(group_line, &message);
915   }
916 
917   // Mixed one- and two-byte header extension.
918   if (desc->extmap_allow_mixed()) {
919     InitAttrLine(kAttributeExtmapAllowMixed, &os);
920     AddLine(os.str(), &message);
921   }
922 
923   // MediaStream semantics
924   InitAttrLine(kAttributeMsidSemantics, &os);
925   os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
926 
927   std::set<std::string> media_stream_ids;
928   const ContentInfo* audio_content = GetFirstAudioContent(desc);
929   if (audio_content)
930     GetMediaStreamIds(audio_content, &media_stream_ids);
931 
932   const ContentInfo* video_content = GetFirstVideoContent(desc);
933   if (video_content)
934     GetMediaStreamIds(video_content, &media_stream_ids);
935 
936   for (const std::string& id : media_stream_ids) {
937     os << " " << id;
938   }
939   AddLine(os.str(), &message);
940 
941   // a=ice-lite
942   //
943   // TODO(deadbeef): It's weird that we need to iterate TransportInfos for
944   // this, when it's a session-level attribute. It really should be moved to a
945   // session-level structure like SessionDescription.
946   for (const cricket::TransportInfo& transport : desc->transport_infos()) {
947     if (transport.description.ice_mode == cricket::ICEMODE_LITE) {
948       InitAttrLine(kAttributeIceLite, &os);
949       AddLine(os.str(), &message);
950       break;
951     }
952   }
953 
954   // Preserve the order of the media contents.
955   int mline_index = -1;
956   for (const ContentInfo& content : desc->contents()) {
957     std::vector<Candidate> candidates;
958     GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
959     BuildMediaDescription(&content, desc->GetTransportInfoByName(content.name),
960                           content.media_description()->type(), candidates,
961                           desc->msid_signaling(), &message);
962   }
963   return message;
964 }
965 
966 // Serializes the passed in IceCandidateInterface to a SDP string.
967 // candidate - The candidate to be serialized.
SdpSerializeCandidate(const IceCandidateInterface & candidate)968 std::string SdpSerializeCandidate(const IceCandidateInterface& candidate) {
969   return SdpSerializeCandidate(candidate.candidate());
970 }
971 
972 // Serializes a cricket Candidate.
SdpSerializeCandidate(const cricket::Candidate & candidate)973 std::string SdpSerializeCandidate(const cricket::Candidate& candidate) {
974   std::string message;
975   std::vector<cricket::Candidate> candidates(1, candidate);
976   BuildCandidate(candidates, true, &message);
977   // From WebRTC draft section 4.8.1.1 candidate-attribute will be
978   // just candidate:<candidate> not a=candidate:<blah>CRLF
979   RTC_DCHECK(message.find("a=") == 0);
980   message.erase(0, 2);
981   RTC_DCHECK(message.find(kLineBreak) == message.size() - 2);
982   message.resize(message.size() - 2);
983   return message;
984 }
985 
SdpDeserialize(const std::string & message,JsepSessionDescription * jdesc,SdpParseError * error)986 bool SdpDeserialize(const std::string& message,
987                     JsepSessionDescription* jdesc,
988                     SdpParseError* error) {
989   std::string session_id;
990   std::string session_version;
991   TransportDescription session_td("", "");
992   RtpHeaderExtensions session_extmaps;
993   rtc::SocketAddress session_connection_addr;
994   auto desc = std::make_unique<cricket::SessionDescription>();
995   size_t current_pos = 0;
996 
997   // Session Description
998   if (!ParseSessionDescription(message, &current_pos, &session_id,
999                                &session_version, &session_td, &session_extmaps,
1000                                &session_connection_addr, desc.get(), error)) {
1001     return false;
1002   }
1003 
1004   // Media Description
1005   std::vector<std::unique_ptr<JsepIceCandidate>> candidates;
1006   if (!ParseMediaDescription(message, session_td, session_extmaps, &current_pos,
1007                              session_connection_addr, desc.get(), &candidates,
1008                              error)) {
1009     return false;
1010   }
1011 
1012   jdesc->Initialize(std::move(desc), session_id, session_version);
1013 
1014   for (const auto& candidate : candidates) {
1015     jdesc->AddCandidate(candidate.get());
1016   }
1017   return true;
1018 }
1019 
SdpDeserializeCandidate(const std::string & message,JsepIceCandidate * jcandidate,SdpParseError * error)1020 bool SdpDeserializeCandidate(const std::string& message,
1021                              JsepIceCandidate* jcandidate,
1022                              SdpParseError* error) {
1023   RTC_DCHECK(jcandidate != NULL);
1024   Candidate candidate;
1025   if (!ParseCandidate(message, &candidate, error, true)) {
1026     return false;
1027   }
1028   jcandidate->SetCandidate(candidate);
1029   return true;
1030 }
1031 
SdpDeserializeCandidate(const std::string & transport_name,const std::string & message,cricket::Candidate * candidate,SdpParseError * error)1032 bool SdpDeserializeCandidate(const std::string& transport_name,
1033                              const std::string& message,
1034                              cricket::Candidate* candidate,
1035                              SdpParseError* error) {
1036   RTC_DCHECK(candidate != nullptr);
1037   if (!ParseCandidate(message, candidate, error, true)) {
1038     return false;
1039   }
1040   candidate->set_transport_name(transport_name);
1041   return true;
1042 }
1043 
ParseCandidate(const std::string & message,Candidate * candidate,SdpParseError * error,bool is_raw)1044 bool ParseCandidate(const std::string& message,
1045                     Candidate* candidate,
1046                     SdpParseError* error,
1047                     bool is_raw) {
1048   RTC_DCHECK(candidate != NULL);
1049 
1050   // Get the first line from |message|.
1051   std::string first_line = message;
1052   size_t pos = 0;
1053   GetLine(message, &pos, &first_line);
1054 
1055   // Makes sure |message| contains only one line.
1056   if (message.size() > first_line.size()) {
1057     std::string left, right;
1058     if (rtc::tokenize_first(message, kNewLineChar, &left, &right) &&
1059         !right.empty()) {
1060       return ParseFailed(message, 0, "Expect one line only", error);
1061     }
1062   }
1063 
1064   // From WebRTC draft section 4.8.1.1 candidate-attribute should be
1065   // candidate:<candidate> when trickled, but we still support
1066   // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
1067   // from the SDP.
1068   if (IsLineType(first_line, kLineTypeAttributes)) {
1069     first_line = first_line.substr(kLinePrefixLength);
1070   }
1071 
1072   std::string attribute_candidate;
1073   std::string candidate_value;
1074 
1075   // |first_line| must be in the form of "candidate:<value>".
1076   if (!rtc::tokenize_first(first_line, kSdpDelimiterColonChar,
1077                            &attribute_candidate, &candidate_value) ||
1078       attribute_candidate != kAttributeCandidate) {
1079     if (is_raw) {
1080       rtc::StringBuilder description;
1081       description << "Expect line: " << kAttributeCandidate
1082                   << ":"
1083                      "<candidate-str>";
1084       return ParseFailed(first_line, 0, description.str(), error);
1085     } else {
1086       return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes,
1087                                    kAttributeCandidate, error);
1088     }
1089   }
1090 
1091   std::vector<std::string> fields;
1092   rtc::split(candidate_value, kSdpDelimiterSpaceChar, &fields);
1093 
1094   // RFC 5245
1095   // a=candidate:<foundation> <component-id> <transport> <priority>
1096   // <connection-address> <port> typ <candidate-types>
1097   // [raddr <connection-address>] [rport <port>]
1098   // *(SP extension-att-name SP extension-att-value)
1099   const size_t expected_min_fields = 8;
1100   if (fields.size() < expected_min_fields ||
1101       (fields[6] != kAttributeCandidateTyp)) {
1102     return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
1103   }
1104   const std::string& foundation = fields[0];
1105 
1106   int component_id = 0;
1107   if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
1108     return false;
1109   }
1110   const std::string& transport = fields[2];
1111   uint32_t priority = 0;
1112   if (!GetValueFromString(first_line, fields[3], &priority, error)) {
1113     return false;
1114   }
1115   const std::string& connection_address = fields[4];
1116   int port = 0;
1117   if (!GetValueFromString(first_line, fields[5], &port, error)) {
1118     return false;
1119   }
1120   if (!IsValidPort(port)) {
1121     return ParseFailed(first_line, "Invalid port number.", error);
1122   }
1123   SocketAddress address(connection_address, port);
1124 
1125   cricket::ProtocolType protocol;
1126   if (!StringToProto(transport.c_str(), &protocol)) {
1127     return ParseFailed(first_line, "Unsupported transport type.", error);
1128   }
1129   bool tcp_protocol = false;
1130   switch (protocol) {
1131     // Supported protocols.
1132     case cricket::PROTO_UDP:
1133       break;
1134     case cricket::PROTO_TCP:
1135     case cricket::PROTO_SSLTCP:
1136       tcp_protocol = true;
1137       break;
1138     default:
1139       return ParseFailed(first_line, "Unsupported transport type.", error);
1140   }
1141 
1142   std::string candidate_type;
1143   const std::string& type = fields[7];
1144   if (type == kCandidateHost) {
1145     candidate_type = cricket::LOCAL_PORT_TYPE;
1146   } else if (type == kCandidateSrflx) {
1147     candidate_type = cricket::STUN_PORT_TYPE;
1148   } else if (type == kCandidateRelay) {
1149     candidate_type = cricket::RELAY_PORT_TYPE;
1150   } else if (type == kCandidatePrflx) {
1151     candidate_type = cricket::PRFLX_PORT_TYPE;
1152   } else {
1153     return ParseFailed(first_line, "Unsupported candidate type.", error);
1154   }
1155 
1156   size_t current_position = expected_min_fields;
1157   SocketAddress related_address;
1158   // The 2 optional fields for related address
1159   // [raddr <connection-address>] [rport <port>]
1160   if (fields.size() >= (current_position + 2) &&
1161       fields[current_position] == kAttributeCandidateRaddr) {
1162     related_address.SetIP(fields[++current_position]);
1163     ++current_position;
1164   }
1165   if (fields.size() >= (current_position + 2) &&
1166       fields[current_position] == kAttributeCandidateRport) {
1167     int port = 0;
1168     if (!GetValueFromString(first_line, fields[++current_position], &port,
1169                             error)) {
1170       return false;
1171     }
1172     if (!IsValidPort(port)) {
1173       return ParseFailed(first_line, "Invalid port number.", error);
1174     }
1175     related_address.SetPort(port);
1176     ++current_position;
1177   }
1178 
1179   // If this is a TCP candidate, it has additional extension as defined in
1180   // RFC 6544.
1181   std::string tcptype;
1182   if (fields.size() >= (current_position + 2) &&
1183       fields[current_position] == kTcpCandidateType) {
1184     tcptype = fields[++current_position];
1185     ++current_position;
1186 
1187     if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
1188         tcptype != cricket::TCPTYPE_PASSIVE_STR &&
1189         tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
1190       return ParseFailed(first_line, "Invalid TCP candidate type.", error);
1191     }
1192 
1193     if (!tcp_protocol) {
1194       return ParseFailed(first_line, "Invalid non-TCP candidate", error);
1195     }
1196   } else if (tcp_protocol) {
1197     // We allow the tcptype to be missing, for backwards compatibility,
1198     // treating it as a passive candidate.
1199     // TODO(bugs.webrtc.org/11466): Treat a missing tcptype as an error?
1200     tcptype = cricket::TCPTYPE_PASSIVE_STR;
1201   }
1202 
1203   // Extension
1204   // Though non-standard, we support the ICE ufrag and pwd being signaled on
1205   // the candidate to avoid issues with confusing which generation a candidate
1206   // belongs to when trickling multiple generations at the same time.
1207   std::string username;
1208   std::string password;
1209   uint32_t generation = 0;
1210   uint16_t network_id = 0;
1211   uint16_t network_cost = 0;
1212   for (size_t i = current_position; i + 1 < fields.size(); ++i) {
1213     // RFC 5245
1214     // *(SP extension-att-name SP extension-att-value)
1215     if (fields[i] == kAttributeCandidateGeneration) {
1216       if (!GetValueFromString(first_line, fields[++i], &generation, error)) {
1217         return false;
1218       }
1219     } else if (fields[i] == kAttributeCandidateUfrag) {
1220       username = fields[++i];
1221     } else if (fields[i] == kAttributeCandidatePwd) {
1222       password = fields[++i];
1223     } else if (fields[i] == kAttributeCandidateNetworkId) {
1224       if (!GetValueFromString(first_line, fields[++i], &network_id, error)) {
1225         return false;
1226       }
1227     } else if (fields[i] == kAttributeCandidateNetworkCost) {
1228       if (!GetValueFromString(first_line, fields[++i], &network_cost, error)) {
1229         return false;
1230       }
1231       network_cost = std::min(network_cost, rtc::kNetworkCostMax);
1232     } else {
1233       // Skip the unknown extension.
1234       ++i;
1235     }
1236   }
1237 
1238   *candidate = Candidate(component_id, cricket::ProtoToString(protocol),
1239                          address, priority, username, password, candidate_type,
1240                          generation, foundation, network_id, network_cost);
1241   candidate->set_related_address(related_address);
1242   candidate->set_tcptype(tcptype);
1243   return true;
1244 }
1245 
ParseIceOptions(const std::string & line,std::vector<std::string> * transport_options,SdpParseError * error)1246 bool ParseIceOptions(const std::string& line,
1247                      std::vector<std::string>* transport_options,
1248                      SdpParseError* error) {
1249   std::string ice_options;
1250   if (!GetValue(line, kAttributeIceOption, &ice_options, error)) {
1251     return false;
1252   }
1253   std::vector<std::string> fields;
1254   rtc::split(ice_options, kSdpDelimiterSpaceChar, &fields);
1255   for (size_t i = 0; i < fields.size(); ++i) {
1256     transport_options->push_back(fields[i]);
1257   }
1258   return true;
1259 }
1260 
ParseSctpPort(const std::string & line,int * sctp_port,SdpParseError * error)1261 bool ParseSctpPort(const std::string& line,
1262                    int* sctp_port,
1263                    SdpParseError* error) {
1264   // draft-ietf-mmusic-sctp-sdp-26
1265   // a=sctp-port
1266   std::vector<std::string> fields;
1267   const size_t expected_min_fields = 2;
1268   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColonChar, &fields);
1269   if (fields.size() < expected_min_fields) {
1270     fields.resize(0);
1271     rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
1272   }
1273   if (fields.size() < expected_min_fields) {
1274     return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1275   }
1276   if (!rtc::FromString(fields[1], sctp_port)) {
1277     return ParseFailed(line, "Invalid sctp port value.", error);
1278   }
1279   return true;
1280 }
1281 
ParseSctpMaxMessageSize(const std::string & line,int * max_message_size,SdpParseError * error)1282 bool ParseSctpMaxMessageSize(const std::string& line,
1283                              int* max_message_size,
1284                              SdpParseError* error) {
1285   // draft-ietf-mmusic-sctp-sdp-26
1286   // a=max-message-size:199999
1287   std::vector<std::string> fields;
1288   const size_t expected_min_fields = 2;
1289   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColonChar, &fields);
1290   if (fields.size() < expected_min_fields) {
1291     return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1292   }
1293   if (!rtc::FromString(fields[1], max_message_size)) {
1294     return ParseFailed(line, "Invalid SCTP max message size.", error);
1295   }
1296   return true;
1297 }
1298 
ParseExtmap(const std::string & line,RtpExtension * extmap,SdpParseError * error)1299 bool ParseExtmap(const std::string& line,
1300                  RtpExtension* extmap,
1301                  SdpParseError* error) {
1302   // RFC 5285
1303   // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1304   std::vector<std::string> fields;
1305   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
1306   const size_t expected_min_fields = 2;
1307   if (fields.size() < expected_min_fields) {
1308     return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
1309   }
1310   std::string uri = fields[1];
1311 
1312   std::string value_direction;
1313   if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) {
1314     return false;
1315   }
1316   std::vector<std::string> sub_fields;
1317   rtc::split(value_direction, kSdpDelimiterSlashChar, &sub_fields);
1318   int value = 0;
1319   if (!GetValueFromString(line, sub_fields[0], &value, error)) {
1320     return false;
1321   }
1322 
1323   bool encrypted = false;
1324   if (uri == RtpExtension::kEncryptHeaderExtensionsUri) {
1325     // RFC 6904
1326     // a=extmap:<value["/"<direction>] urn:ietf:params:rtp-hdrext:encrypt <URI>
1327     //     <extensionattributes>
1328     const size_t expected_min_fields_encrypted = expected_min_fields + 1;
1329     if (fields.size() < expected_min_fields_encrypted) {
1330       return ParseFailedExpectMinFieldNum(line, expected_min_fields_encrypted,
1331                                           error);
1332     }
1333 
1334     encrypted = true;
1335     uri = fields[2];
1336     if (uri == RtpExtension::kEncryptHeaderExtensionsUri) {
1337       return ParseFailed(line, "Recursive encrypted header.", error);
1338     }
1339   }
1340 
1341   *extmap = RtpExtension(uri, value, encrypted);
1342   return true;
1343 }
1344 
BuildSctpContentAttributes(std::string * message,const cricket::SctpDataContentDescription * data_desc)1345 static void BuildSctpContentAttributes(
1346     std::string* message,
1347     const cricket::SctpDataContentDescription* data_desc) {
1348   rtc::StringBuilder os;
1349   if (data_desc->use_sctpmap()) {
1350     // draft-ietf-mmusic-sctp-sdp-04
1351     // a=sctpmap:sctpmap-number  protocol  [streams]
1352     rtc::StringBuilder os;
1353     InitAttrLine(kAttributeSctpmap, &os);
1354     os << kSdpDelimiterColon << data_desc->port() << kSdpDelimiterSpace
1355        << kDefaultSctpmapProtocol << kSdpDelimiterSpace
1356        << cricket::kMaxSctpStreams;
1357     AddLine(os.str(), message);
1358   } else {
1359     // draft-ietf-mmusic-sctp-sdp-23
1360     // a=sctp-port:<port>
1361     InitAttrLine(kAttributeSctpPort, &os);
1362     os << kSdpDelimiterColon << data_desc->port();
1363     AddLine(os.str(), message);
1364     if (data_desc->max_message_size() != kDefaultSctpMaxMessageSize) {
1365       InitAttrLine(kAttributeMaxMessageSize, &os);
1366       os << kSdpDelimiterColon << data_desc->max_message_size();
1367       AddLine(os.str(), message);
1368     }
1369   }
1370 }
1371 
BuildMediaDescription(const ContentInfo * content_info,const TransportInfo * transport_info,const cricket::MediaType media_type,const std::vector<Candidate> & candidates,int msid_signaling,std::string * message)1372 void BuildMediaDescription(const ContentInfo* content_info,
1373                            const TransportInfo* transport_info,
1374                            const cricket::MediaType media_type,
1375                            const std::vector<Candidate>& candidates,
1376                            int msid_signaling,
1377                            std::string* message) {
1378   RTC_DCHECK(message != NULL);
1379   if (content_info == NULL || message == NULL) {
1380     return;
1381   }
1382   rtc::StringBuilder os;
1383   const MediaContentDescription* media_desc = content_info->media_description();
1384   RTC_DCHECK(media_desc);
1385 
1386   // RFC 4566
1387   // m=<media> <port> <proto> <fmt>
1388   // fmt is a list of payload type numbers that MAY be used in the session.
1389   std::string type;
1390   std::string fmt;
1391   if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1392     type = kMediaTypeVideo;
1393     const VideoContentDescription* video_desc = media_desc->as_video();
1394     for (const cricket::VideoCodec& codec : video_desc->codecs()) {
1395       fmt.append(" ");
1396       fmt.append(rtc::ToString(codec.id));
1397     }
1398   } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1399     type = kMediaTypeAudio;
1400     const AudioContentDescription* audio_desc = media_desc->as_audio();
1401     for (const cricket::AudioCodec& codec : audio_desc->codecs()) {
1402       fmt.append(" ");
1403       fmt.append(rtc::ToString(codec.id));
1404     }
1405   } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1406     type = kMediaTypeData;
1407     const cricket::SctpDataContentDescription* sctp_data_desc =
1408         media_desc->as_sctp();
1409     if (sctp_data_desc) {
1410       fmt.append(" ");
1411 
1412       if (sctp_data_desc->use_sctpmap()) {
1413         fmt.append(rtc::ToString(sctp_data_desc->port()));
1414       } else {
1415         fmt.append(kDefaultSctpmapProtocol);
1416       }
1417     } else {
1418       const RtpDataContentDescription* rtp_data_desc =
1419           media_desc->as_rtp_data();
1420       for (const cricket::RtpDataCodec& codec : rtp_data_desc->codecs()) {
1421         fmt.append(" ");
1422         fmt.append(rtc::ToString(codec.id));
1423       }
1424     }
1425   } else if (media_type == cricket::MEDIA_TYPE_UNSUPPORTED) {
1426     const UnsupportedContentDescription* unsupported_desc =
1427         media_desc->as_unsupported();
1428     type = unsupported_desc->media_type();
1429   } else {
1430     RTC_NOTREACHED();
1431   }
1432   // The fmt must never be empty. If no codecs are found, set the fmt attribute
1433   // to 0.
1434   if (fmt.empty()) {
1435     fmt = " 0";
1436   }
1437 
1438   // The port number in the m line will be updated later when associated with
1439   // the candidates.
1440   //
1441   // A port value of 0 indicates that the m= section is rejected.
1442   // RFC 3264
1443   // To reject an offered stream, the port number in the corresponding stream in
1444   // the answer MUST be set to zero.
1445   //
1446   // However, the BUNDLE draft adds a new meaning to port zero, when used along
1447   // with a=bundle-only.
1448   std::string port = kDummyPort;
1449   if (content_info->rejected || content_info->bundle_only) {
1450     port = kMediaPortRejected;
1451   } else if (!media_desc->connection_address().IsNil()) {
1452     port = rtc::ToString(media_desc->connection_address().port());
1453   }
1454 
1455   rtc::SSLFingerprint* fp =
1456       (transport_info) ? transport_info->description.identity_fingerprint.get()
1457                        : NULL;
1458 
1459   // Add the m and c lines.
1460   InitLine(kLineTypeMedia, type, &os);
1461   os << " " << port << " " << media_desc->protocol() << fmt;
1462   AddLine(os.str(), message);
1463 
1464   InitLine(kLineTypeConnection, kConnectionNettype, &os);
1465   if (media_desc->connection_address().IsNil()) {
1466     os << " " << kConnectionIpv4Addrtype << " " << kDummyAddress;
1467   } else if (media_desc->connection_address().family() == AF_INET) {
1468     os << " " << kConnectionIpv4Addrtype << " "
1469        << media_desc->connection_address().ipaddr().ToString();
1470   } else if (media_desc->connection_address().family() == AF_INET6) {
1471     os << " " << kConnectionIpv6Addrtype << " "
1472        << media_desc->connection_address().ipaddr().ToString();
1473   } else {
1474     os << " " << kConnectionIpv4Addrtype << " " << kDummyAddress;
1475   }
1476   AddLine(os.str(), message);
1477 
1478   // RFC 4566
1479   // b=AS:<bandwidth> or
1480   // b=TIAS:<bandwidth>
1481   int bandwidth = media_desc->bandwidth();
1482   std::string bandwidth_type = media_desc->bandwidth_type();
1483   if (bandwidth_type == kApplicationSpecificBandwidth && bandwidth >= 1000) {
1484     InitLine(kLineTypeSessionBandwidth, bandwidth_type, &os);
1485     bandwidth /= 1000;
1486     os << kSdpDelimiterColon << bandwidth;
1487     AddLine(os.str(), message);
1488   } else if (bandwidth_type == kTransportSpecificBandwidth && bandwidth > 0) {
1489     InitLine(kLineTypeSessionBandwidth, bandwidth_type, &os);
1490     os << kSdpDelimiterColon << bandwidth;
1491     AddLine(os.str(), message);
1492   }
1493 
1494   // Add the a=bundle-only line.
1495   if (content_info->bundle_only) {
1496     InitAttrLine(kAttributeBundleOnly, &os);
1497     AddLine(os.str(), message);
1498   }
1499 
1500   // Add the a=rtcp line.
1501   if (cricket::IsRtpProtocol(media_desc->protocol())) {
1502     std::string rtcp_line = GetRtcpLine(candidates);
1503     if (!rtcp_line.empty()) {
1504       AddLine(rtcp_line, message);
1505     }
1506   }
1507 
1508   // Build the a=candidate lines. We don't include ufrag and pwd in the
1509   // candidates in the SDP to avoid redundancy.
1510   BuildCandidate(candidates, false, message);
1511 
1512   // Use the transport_info to build the media level ice-ufrag and ice-pwd.
1513   if (transport_info) {
1514     // RFC 5245
1515     // ice-pwd-att           = "ice-pwd" ":" password
1516     // ice-ufrag-att         = "ice-ufrag" ":" ufrag
1517     // ice-ufrag
1518     if (!transport_info->description.ice_ufrag.empty()) {
1519       InitAttrLine(kAttributeIceUfrag, &os);
1520       os << kSdpDelimiterColon << transport_info->description.ice_ufrag;
1521       AddLine(os.str(), message);
1522     }
1523     // ice-pwd
1524     if (!transport_info->description.ice_pwd.empty()) {
1525       InitAttrLine(kAttributeIcePwd, &os);
1526       os << kSdpDelimiterColon << transport_info->description.ice_pwd;
1527       AddLine(os.str(), message);
1528     }
1529 
1530     // draft-petithuguenin-mmusic-ice-attributes-level-03
1531     BuildIceOptions(transport_info->description.transport_options, message);
1532 
1533     // RFC 4572
1534     // fingerprint-attribute  =
1535     //   "fingerprint" ":" hash-func SP fingerprint
1536     if (fp) {
1537       // Insert the fingerprint attribute.
1538       InitAttrLine(kAttributeFingerprint, &os);
1539       os << kSdpDelimiterColon << fp->algorithm << kSdpDelimiterSpace
1540          << fp->GetRfc4572Fingerprint();
1541       AddLine(os.str(), message);
1542 
1543       // Inserting setup attribute.
1544       if (transport_info->description.connection_role !=
1545           cricket::CONNECTIONROLE_NONE) {
1546         // Making sure we are not using "passive" mode.
1547         cricket::ConnectionRole role =
1548             transport_info->description.connection_role;
1549         std::string dtls_role_str;
1550         const bool success =
1551             cricket::ConnectionRoleToString(role, &dtls_role_str);
1552         RTC_DCHECK(success);
1553         InitAttrLine(kAttributeSetup, &os);
1554         os << kSdpDelimiterColon << dtls_role_str;
1555         AddLine(os.str(), message);
1556       }
1557     }
1558   }
1559 
1560   // RFC 3388
1561   // mid-attribute      = "a=mid:" identification-tag
1562   // identification-tag = token
1563   // Use the content name as the mid identification-tag.
1564   InitAttrLine(kAttributeMid, &os);
1565   os << kSdpDelimiterColon << content_info->name;
1566   AddLine(os.str(), message);
1567 
1568   if (cricket::IsDtlsSctp(media_desc->protocol())) {
1569     const cricket::SctpDataContentDescription* data_desc =
1570         media_desc->as_sctp();
1571     BuildSctpContentAttributes(message, data_desc);
1572   } else if (cricket::IsRtpProtocol(media_desc->protocol())) {
1573     BuildRtpContentAttributes(media_desc, media_type, msid_signaling, message);
1574   }
1575 }
1576 
BuildRtpContentAttributes(const MediaContentDescription * media_desc,const cricket::MediaType media_type,int msid_signaling,std::string * message)1577 void BuildRtpContentAttributes(const MediaContentDescription* media_desc,
1578                                const cricket::MediaType media_type,
1579                                int msid_signaling,
1580                                std::string* message) {
1581   SdpSerializer serializer;
1582   rtc::StringBuilder os;
1583   // RFC 8285
1584   // a=extmap-allow-mixed
1585   // The attribute MUST be either on session level or media level. We support
1586   // responding on both levels, however, we don't respond on media level if it's
1587   // set on session level.
1588   if (media_desc->extmap_allow_mixed_enum() ==
1589       MediaContentDescription::kMedia) {
1590     InitAttrLine(kAttributeExtmapAllowMixed, &os);
1591     AddLine(os.str(), message);
1592   }
1593   // RFC 8285
1594   // a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
1595   // The definitions MUST be either all session level or all media level. This
1596   // implementation uses all media level.
1597   for (size_t i = 0; i < media_desc->rtp_header_extensions().size(); ++i) {
1598     const RtpExtension& extension = media_desc->rtp_header_extensions()[i];
1599     InitAttrLine(kAttributeExtmap, &os);
1600     os << kSdpDelimiterColon << extension.id;
1601     if (extension.encrypt) {
1602       os << kSdpDelimiterSpace << RtpExtension::kEncryptHeaderExtensionsUri;
1603     }
1604     os << kSdpDelimiterSpace << extension.uri;
1605     AddLine(os.str(), message);
1606   }
1607 
1608   // RFC 3264
1609   // a=sendrecv || a=sendonly || a=sendrecv || a=inactive
1610   switch (media_desc->direction()) {
1611     // Special case that for sdp purposes should be treated same as inactive.
1612     case RtpTransceiverDirection::kStopped:
1613     case RtpTransceiverDirection::kInactive:
1614       InitAttrLine(kAttributeInactive, &os);
1615       break;
1616     case RtpTransceiverDirection::kSendOnly:
1617       InitAttrLine(kAttributeSendOnly, &os);
1618       break;
1619     case RtpTransceiverDirection::kRecvOnly:
1620       InitAttrLine(kAttributeRecvOnly, &os);
1621       break;
1622     case RtpTransceiverDirection::kSendRecv:
1623       InitAttrLine(kAttributeSendRecv, &os);
1624       break;
1625     default:
1626       RTC_NOTREACHED();
1627       InitAttrLine(kAttributeSendRecv, &os);
1628       break;
1629   }
1630   AddLine(os.str(), message);
1631 
1632   // Specified in https://datatracker.ietf.org/doc/draft-ietf-mmusic-msid/16/
1633   // a=msid:<msid-id> <msid-appdata>
1634   // The msid-id is a 1*64 token char representing the media stream id, and the
1635   // msid-appdata is a 1*64 token char representing the track id. There is a
1636   // line for every media stream, with a special msid-id value of "-"
1637   // representing no streams. The value of "msid-appdata" MUST be identical for
1638   // all lines.
1639   if (msid_signaling & cricket::kMsidSignalingMediaSection) {
1640     const StreamParamsVec& streams = media_desc->streams();
1641     if (streams.size() == 1u) {
1642       const StreamParams& track = streams[0];
1643       std::vector<std::string> stream_ids = track.stream_ids();
1644       if (stream_ids.empty()) {
1645         stream_ids.push_back(kNoStreamMsid);
1646       }
1647       for (const std::string& stream_id : stream_ids) {
1648         InitAttrLine(kAttributeMsid, &os);
1649         os << kSdpDelimiterColon << stream_id << kSdpDelimiterSpace << track.id;
1650         AddLine(os.str(), message);
1651       }
1652     } else if (streams.size() > 1u) {
1653       RTC_LOG(LS_WARNING)
1654           << "Trying to serialize Unified Plan SDP with more than "
1655              "one track in a media section. Omitting 'a=msid'.";
1656     }
1657   }
1658 
1659   // RFC 5761
1660   // a=rtcp-mux
1661   if (media_desc->rtcp_mux()) {
1662     InitAttrLine(kAttributeRtcpMux, &os);
1663     AddLine(os.str(), message);
1664   }
1665 
1666   // RFC 5506
1667   // a=rtcp-rsize
1668   if (media_desc->rtcp_reduced_size()) {
1669     InitAttrLine(kAttributeRtcpReducedSize, &os);
1670     AddLine(os.str(), message);
1671   }
1672 
1673   if (media_desc->conference_mode()) {
1674     InitAttrLine(kAttributeXGoogleFlag, &os);
1675     os << kSdpDelimiterColon << kValueConference;
1676     AddLine(os.str(), message);
1677   }
1678 
1679   if (media_desc->remote_estimate()) {
1680     InitAttrLine(kAttributeRtcpRemoteEstimate, &os);
1681     AddLine(os.str(), message);
1682   }
1683 
1684   // RFC 4568
1685   // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
1686   for (const CryptoParams& crypto_params : media_desc->cryptos()) {
1687     InitAttrLine(kAttributeCrypto, &os);
1688     os << kSdpDelimiterColon << crypto_params.tag << " "
1689        << crypto_params.cipher_suite << " " << crypto_params.key_params;
1690     if (!crypto_params.session_params.empty()) {
1691       os << " " << crypto_params.session_params;
1692     }
1693     AddLine(os.str(), message);
1694   }
1695 
1696   // RFC 4566
1697   // a=rtpmap:<payload type> <encoding name>/<clock rate>
1698   // [/<encodingparameters>]
1699   BuildRtpMap(media_desc, media_type, message);
1700 
1701   for (const StreamParams& track : media_desc->streams()) {
1702     // Build the ssrc-group lines.
1703     for (const SsrcGroup& ssrc_group : track.ssrc_groups) {
1704       // RFC 5576
1705       // a=ssrc-group:<semantics> <ssrc-id> ...
1706       if (ssrc_group.ssrcs.empty()) {
1707         continue;
1708       }
1709       InitAttrLine(kAttributeSsrcGroup, &os);
1710       os << kSdpDelimiterColon << ssrc_group.semantics;
1711       for (uint32_t ssrc : ssrc_group.ssrcs) {
1712         os << kSdpDelimiterSpace << rtc::ToString(ssrc);
1713       }
1714       AddLine(os.str(), message);
1715     }
1716     // Build the ssrc lines for each ssrc.
1717     for (uint32_t ssrc : track.ssrcs) {
1718       // RFC 5576
1719       // a=ssrc:<ssrc-id> cname:<value>
1720       AddSsrcLine(ssrc, kSsrcAttributeCname, track.cname, message);
1721 
1722       if (msid_signaling & cricket::kMsidSignalingSsrcAttribute) {
1723         // draft-alvestrand-mmusic-msid-00
1724         // a=ssrc:<ssrc-id> msid:identifier [appdata]
1725         // The appdata consists of the "id" attribute of a MediaStreamTrack,
1726         // which corresponds to the "id" attribute of StreamParams.
1727         // Since a=ssrc msid signaling is used in Plan B SDP semantics, and
1728         // multiple stream ids are not supported for Plan B, we are only adding
1729         // a line for the first media stream id here.
1730         const std::string& track_stream_id = track.first_stream_id();
1731         // We use a special msid-id value of "-" to represent no streams,
1732         // for Unified Plan compatibility. Plan B will always have a
1733         // track_stream_id.
1734         const std::string& stream_id =
1735             track_stream_id.empty() ? kNoStreamMsid : track_stream_id;
1736         InitAttrLine(kAttributeSsrc, &os);
1737         os << kSdpDelimiterColon << ssrc << kSdpDelimiterSpace
1738            << kSsrcAttributeMsid << kSdpDelimiterColon << stream_id
1739            << kSdpDelimiterSpace << track.id;
1740         AddLine(os.str(), message);
1741 
1742         // TODO(ronghuawu): Remove below code which is for backward
1743         // compatibility.
1744         // draft-alvestrand-rtcweb-mid-01
1745         // a=ssrc:<ssrc-id> mslabel:<value>
1746         // The label isn't yet defined.
1747         // a=ssrc:<ssrc-id> label:<value>
1748         AddSsrcLine(ssrc, kSsrcAttributeMslabel, stream_id, message);
1749         AddSsrcLine(ssrc, kSSrcAttributeLabel, track.id, message);
1750       }
1751     }
1752 
1753     // Build the rid lines for each layer of the track
1754     for (const RidDescription& rid_description : track.rids()) {
1755       InitAttrLine(kAttributeRid, &os);
1756       os << kSdpDelimiterColon
1757          << serializer.SerializeRidDescription(rid_description);
1758       AddLine(os.str(), message);
1759     }
1760   }
1761 
1762   for (const RidDescription& rid_description : media_desc->receive_rids()) {
1763     InitAttrLine(kAttributeRid, &os);
1764     os << kSdpDelimiterColon
1765        << serializer.SerializeRidDescription(rid_description);
1766     AddLine(os.str(), message);
1767   }
1768 
1769   // Simulcast (a=simulcast)
1770   // https://tools.ietf.org/html/draft-ietf-mmusic-sdp-simulcast-13#section-5.1
1771   if (media_desc->HasSimulcast()) {
1772     const auto& simulcast = media_desc->simulcast_description();
1773     InitAttrLine(kAttributeSimulcast, &os);
1774     os << kSdpDelimiterColon
1775        << serializer.SerializeSimulcastDescription(simulcast);
1776     AddLine(os.str(), message);
1777   }
1778 }
1779 
WriteFmtpHeader(int payload_type,rtc::StringBuilder * os)1780 void WriteFmtpHeader(int payload_type, rtc::StringBuilder* os) {
1781   // fmtp header: a=fmtp:|payload_type| <parameters>
1782   // Add a=fmtp
1783   InitAttrLine(kAttributeFmtp, os);
1784   // Add :|payload_type|
1785   *os << kSdpDelimiterColon << payload_type;
1786 }
1787 
WritePacketizationHeader(int payload_type,rtc::StringBuilder * os)1788 void WritePacketizationHeader(int payload_type, rtc::StringBuilder* os) {
1789   // packetization header: a=packetization:|payload_type| <packetization_format>
1790   // Add a=packetization
1791   InitAttrLine(kAttributePacketization, os);
1792   // Add :|payload_type|
1793   *os << kSdpDelimiterColon << payload_type;
1794 }
1795 
WriteRtcpFbHeader(int payload_type,rtc::StringBuilder * os)1796 void WriteRtcpFbHeader(int payload_type, rtc::StringBuilder* os) {
1797   // rtcp-fb header: a=rtcp-fb:|payload_type|
1798   // <parameters>/<ccm <ccm_parameters>>
1799   // Add a=rtcp-fb
1800   InitAttrLine(kAttributeRtcpFb, os);
1801   // Add :
1802   *os << kSdpDelimiterColon;
1803   if (payload_type == kWildcardPayloadType) {
1804     *os << "*";
1805   } else {
1806     *os << payload_type;
1807   }
1808 }
1809 
WriteFmtpParameter(const std::string & parameter_name,const std::string & parameter_value,rtc::StringBuilder * os)1810 void WriteFmtpParameter(const std::string& parameter_name,
1811                         const std::string& parameter_value,
1812                         rtc::StringBuilder* os) {
1813   if (parameter_name == "") {
1814     // RFC 2198 and RFC 4733 don't use key-value pairs.
1815     *os << parameter_value;
1816   } else {
1817     // fmtp parameters: |parameter_name|=|parameter_value|
1818     *os << parameter_name << kSdpDelimiterEqual << parameter_value;
1819   }
1820 }
1821 
IsFmtpParam(const std::string & name)1822 bool IsFmtpParam(const std::string& name) {
1823   // RFC 4855, section 3 specifies the mapping of media format parameters to SDP
1824   // parameters. Only ptime, maxptime, channels and rate are placed outside of
1825   // the fmtp line. In WebRTC, channels and rate are already handled separately
1826   // and thus not included in the CodecParameterMap.
1827   return name != kCodecParamPTime && name != kCodecParamMaxPTime;
1828 }
1829 
WriteFmtpParameters(const cricket::CodecParameterMap & parameters,rtc::StringBuilder * os)1830 bool WriteFmtpParameters(const cricket::CodecParameterMap& parameters,
1831                          rtc::StringBuilder* os) {
1832   bool empty = true;
1833   const char* delimiter = "";  // No delimiter before first parameter.
1834   for (const auto& entry : parameters) {
1835     const std::string& key = entry.first;
1836     const std::string& value = entry.second;
1837 
1838     if (IsFmtpParam(key)) {
1839       *os << delimiter;
1840       // A semicolon before each subsequent parameter.
1841       delimiter = kSdpDelimiterSemicolon;
1842       WriteFmtpParameter(key, value, os);
1843       empty = false;
1844     }
1845   }
1846 
1847   return !empty;
1848 }
1849 
1850 template <class T>
AddFmtpLine(const T & codec,std::string * message)1851 void AddFmtpLine(const T& codec, std::string* message) {
1852   rtc::StringBuilder os;
1853   WriteFmtpHeader(codec.id, &os);
1854   os << kSdpDelimiterSpace;
1855   // Create FMTP line and check that it's nonempty.
1856   if (WriteFmtpParameters(codec.params, &os)) {
1857     AddLine(os.str(), message);
1858   }
1859   return;
1860 }
1861 
1862 template <class T>
AddPacketizationLine(const T & codec,std::string * message)1863 void AddPacketizationLine(const T& codec, std::string* message) {
1864   if (!codec.packetization) {
1865     return;
1866   }
1867   rtc::StringBuilder os;
1868   WritePacketizationHeader(codec.id, &os);
1869   os << " " << *codec.packetization;
1870   AddLine(os.str(), message);
1871 }
1872 
1873 template <class T>
AddRtcpFbLines(const T & codec,std::string * message)1874 void AddRtcpFbLines(const T& codec, std::string* message) {
1875   for (const cricket::FeedbackParam& param : codec.feedback_params.params()) {
1876     rtc::StringBuilder os;
1877     WriteRtcpFbHeader(codec.id, &os);
1878     os << " " << param.id();
1879     if (!param.param().empty()) {
1880       os << " " << param.param();
1881     }
1882     AddLine(os.str(), message);
1883   }
1884 }
1885 
GetMinValue(const std::vector<int> & values,int * value)1886 bool GetMinValue(const std::vector<int>& values, int* value) {
1887   if (values.empty()) {
1888     return false;
1889   }
1890   auto it = absl::c_min_element(values);
1891   *value = *it;
1892   return true;
1893 }
1894 
GetParameter(const std::string & name,const cricket::CodecParameterMap & params,int * value)1895 bool GetParameter(const std::string& name,
1896                   const cricket::CodecParameterMap& params,
1897                   int* value) {
1898   std::map<std::string, std::string>::const_iterator found = params.find(name);
1899   if (found == params.end()) {
1900     return false;
1901   }
1902   if (!rtc::FromString(found->second, value)) {
1903     return false;
1904   }
1905   return true;
1906 }
1907 
BuildRtpMap(const MediaContentDescription * media_desc,const cricket::MediaType media_type,std::string * message)1908 void BuildRtpMap(const MediaContentDescription* media_desc,
1909                  const cricket::MediaType media_type,
1910                  std::string* message) {
1911   RTC_DCHECK(message != NULL);
1912   RTC_DCHECK(media_desc != NULL);
1913   rtc::StringBuilder os;
1914   if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1915     for (const cricket::VideoCodec& codec : media_desc->as_video()->codecs()) {
1916       // RFC 4566
1917       // a=rtpmap:<payload type> <encoding name>/<clock rate>
1918       // [/<encodingparameters>]
1919       if (codec.id != kWildcardPayloadType) {
1920         InitAttrLine(kAttributeRtpmap, &os);
1921         os << kSdpDelimiterColon << codec.id << " " << codec.name << "/"
1922            << cricket::kVideoCodecClockrate;
1923         AddLine(os.str(), message);
1924       }
1925       AddPacketizationLine(codec, message);
1926       AddRtcpFbLines(codec, message);
1927       AddFmtpLine(codec, message);
1928     }
1929   } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1930     std::vector<int> ptimes;
1931     std::vector<int> maxptimes;
1932     int max_minptime = 0;
1933     for (const cricket::AudioCodec& codec : media_desc->as_audio()->codecs()) {
1934       RTC_DCHECK(!codec.name.empty());
1935       // RFC 4566
1936       // a=rtpmap:<payload type> <encoding name>/<clock rate>
1937       // [/<encodingparameters>]
1938       InitAttrLine(kAttributeRtpmap, &os);
1939       os << kSdpDelimiterColon << codec.id << " ";
1940       os << codec.name << "/" << codec.clockrate;
1941       if (codec.channels != 1) {
1942         os << "/" << codec.channels;
1943       }
1944       AddLine(os.str(), message);
1945       AddRtcpFbLines(codec, message);
1946       AddFmtpLine(codec, message);
1947       int minptime = 0;
1948       if (GetParameter(kCodecParamMinPTime, codec.params, &minptime)) {
1949         max_minptime = std::max(minptime, max_minptime);
1950       }
1951       int ptime;
1952       if (GetParameter(kCodecParamPTime, codec.params, &ptime)) {
1953         ptimes.push_back(ptime);
1954       }
1955       int maxptime;
1956       if (GetParameter(kCodecParamMaxPTime, codec.params, &maxptime)) {
1957         maxptimes.push_back(maxptime);
1958       }
1959     }
1960     // Populate the maxptime attribute with the smallest maxptime of all codecs
1961     // under the same m-line.
1962     int min_maxptime = INT_MAX;
1963     if (GetMinValue(maxptimes, &min_maxptime)) {
1964       AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message);
1965     }
1966     RTC_DCHECK(min_maxptime > max_minptime);
1967     // Populate the ptime attribute with the smallest ptime or the largest
1968     // minptime, whichever is the largest, for all codecs under the same m-line.
1969     int ptime = INT_MAX;
1970     if (GetMinValue(ptimes, &ptime)) {
1971       ptime = std::min(ptime, min_maxptime);
1972       ptime = std::max(ptime, max_minptime);
1973       AddAttributeLine(kCodecParamPTime, ptime, message);
1974     }
1975   } else if (media_type == cricket::MEDIA_TYPE_DATA) {
1976     if (media_desc->as_rtp_data()) {
1977       for (const cricket::RtpDataCodec& codec :
1978            media_desc->as_rtp_data()->codecs()) {
1979         // RFC 4566
1980         // a=rtpmap:<payload type> <encoding name>/<clock rate>
1981         // [/<encodingparameters>]
1982         InitAttrLine(kAttributeRtpmap, &os);
1983         os << kSdpDelimiterColon << codec.id << " " << codec.name << "/"
1984            << codec.clockrate;
1985         AddLine(os.str(), message);
1986       }
1987     }
1988   }
1989 }
1990 
BuildCandidate(const std::vector<Candidate> & candidates,bool include_ufrag,std::string * message)1991 void BuildCandidate(const std::vector<Candidate>& candidates,
1992                     bool include_ufrag,
1993                     std::string* message) {
1994   rtc::StringBuilder os;
1995 
1996   for (const Candidate& candidate : candidates) {
1997     // RFC 5245
1998     // a=candidate:<foundation> <component-id> <transport> <priority>
1999     // <connection-address> <port> typ <candidate-types>
2000     // [raddr <connection-address>] [rport <port>]
2001     // *(SP extension-att-name SP extension-att-value)
2002     std::string type;
2003     // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay"
2004     if (candidate.type() == cricket::LOCAL_PORT_TYPE) {
2005       type = kCandidateHost;
2006     } else if (candidate.type() == cricket::STUN_PORT_TYPE) {
2007       type = kCandidateSrflx;
2008     } else if (candidate.type() == cricket::RELAY_PORT_TYPE) {
2009       type = kCandidateRelay;
2010     } else if (candidate.type() == cricket::PRFLX_PORT_TYPE) {
2011       type = kCandidatePrflx;
2012       // Peer reflexive candidate may be signaled for being removed.
2013     } else {
2014       RTC_NOTREACHED();
2015       // Never write out candidates if we don't know the type.
2016       continue;
2017     }
2018 
2019     InitAttrLine(kAttributeCandidate, &os);
2020     os << kSdpDelimiterColon << candidate.foundation() << " "
2021        << candidate.component() << " " << candidate.protocol() << " "
2022        << candidate.priority() << " "
2023        << (candidate.address().ipaddr().IsNil()
2024                ? candidate.address().hostname()
2025                : candidate.address().ipaddr().ToString())
2026        << " " << candidate.address().PortAsString() << " "
2027        << kAttributeCandidateTyp << " " << type << " ";
2028 
2029     // Related address
2030     if (!candidate.related_address().IsNil()) {
2031       os << kAttributeCandidateRaddr << " "
2032          << candidate.related_address().ipaddr().ToString() << " "
2033          << kAttributeCandidateRport << " "
2034          << candidate.related_address().PortAsString() << " ";
2035     }
2036 
2037     // Note that we allow the tcptype to be missing, for backwards
2038     // compatibility; the implementation treats this as a passive candidate.
2039     // TODO(bugs.webrtc.org/11466): Treat a missing tcptype as an error?
2040     if (candidate.protocol() == cricket::TCP_PROTOCOL_NAME &&
2041         !candidate.tcptype().empty()) {
2042       os << kTcpCandidateType << " " << candidate.tcptype() << " ";
2043     }
2044 
2045     // Extensions
2046     os << kAttributeCandidateGeneration << " " << candidate.generation();
2047     if (include_ufrag && !candidate.username().empty()) {
2048       os << " " << kAttributeCandidateUfrag << " " << candidate.username();
2049     }
2050     if (candidate.network_id() > 0) {
2051       os << " " << kAttributeCandidateNetworkId << " "
2052          << candidate.network_id();
2053     }
2054     if (candidate.network_cost() > 0) {
2055       os << " " << kAttributeCandidateNetworkCost << " "
2056          << candidate.network_cost();
2057     }
2058 
2059     AddLine(os.str(), message);
2060   }
2061 }
2062 
BuildIceOptions(const std::vector<std::string> & transport_options,std::string * message)2063 void BuildIceOptions(const std::vector<std::string>& transport_options,
2064                      std::string* message) {
2065   if (!transport_options.empty()) {
2066     rtc::StringBuilder os;
2067     InitAttrLine(kAttributeIceOption, &os);
2068     os << kSdpDelimiterColon << transport_options[0];
2069     for (size_t i = 1; i < transport_options.size(); ++i) {
2070       os << kSdpDelimiterSpace << transport_options[i];
2071     }
2072     AddLine(os.str(), message);
2073   }
2074 }
2075 
ParseConnectionData(const std::string & line,rtc::SocketAddress * addr,SdpParseError * error)2076 bool ParseConnectionData(const std::string& line,
2077                          rtc::SocketAddress* addr,
2078                          SdpParseError* error) {
2079   // Parse the line from left to right.
2080   std::string token;
2081   std::string rightpart;
2082   // RFC 4566
2083   // c=<nettype> <addrtype> <connection-address>
2084   // Skip the "c="
2085   if (!rtc::tokenize_first(line, kSdpDelimiterEqualChar, &token, &rightpart)) {
2086     return ParseFailed(line, "Failed to parse the network type.", error);
2087   }
2088 
2089   // Extract and verify the <nettype>
2090   if (!rtc::tokenize_first(rightpart, kSdpDelimiterSpaceChar, &token,
2091                            &rightpart) ||
2092       token != kConnectionNettype) {
2093     return ParseFailed(line,
2094                        "Failed to parse the connection data. The network type "
2095                        "is not currently supported.",
2096                        error);
2097   }
2098 
2099   // Extract the "<addrtype>" and "<connection-address>".
2100   if (!rtc::tokenize_first(rightpart, kSdpDelimiterSpaceChar, &token,
2101                            &rightpart)) {
2102     return ParseFailed(line, "Failed to parse the address type.", error);
2103   }
2104 
2105   // The rightpart part should be the IP address without the slash which is used
2106   // for multicast.
2107   if (rightpart.find('/') != std::string::npos) {
2108     return ParseFailed(line,
2109                        "Failed to parse the connection data. Multicast is not "
2110                        "currently supported.",
2111                        error);
2112   }
2113   addr->SetIP(rightpart);
2114 
2115   // Verify that the addrtype matches the type of the parsed address.
2116   if ((addr->family() == AF_INET && token != "IP4") ||
2117       (addr->family() == AF_INET6 && token != "IP6")) {
2118     addr->Clear();
2119     return ParseFailed(
2120         line,
2121         "Failed to parse the connection data. The address type is mismatching.",
2122         error);
2123   }
2124   return true;
2125 }
2126 
ParseSessionDescription(const std::string & message,size_t * pos,std::string * session_id,std::string * session_version,TransportDescription * session_td,RtpHeaderExtensions * session_extmaps,rtc::SocketAddress * connection_addr,cricket::SessionDescription * desc,SdpParseError * error)2127 bool ParseSessionDescription(const std::string& message,
2128                              size_t* pos,
2129                              std::string* session_id,
2130                              std::string* session_version,
2131                              TransportDescription* session_td,
2132                              RtpHeaderExtensions* session_extmaps,
2133                              rtc::SocketAddress* connection_addr,
2134                              cricket::SessionDescription* desc,
2135                              SdpParseError* error) {
2136   std::string line;
2137 
2138   desc->set_msid_supported(false);
2139   desc->set_extmap_allow_mixed(false);
2140   // RFC 4566
2141   // v=  (protocol version)
2142   if (!GetLineWithType(message, pos, &line, kLineTypeVersion)) {
2143     return ParseFailedExpectLine(message, *pos, kLineTypeVersion, std::string(),
2144                                  error);
2145   }
2146   // RFC 4566
2147   // o=<username> <sess-id> <sess-version> <nettype> <addrtype>
2148   // <unicast-address>
2149   if (!GetLineWithType(message, pos, &line, kLineTypeOrigin)) {
2150     return ParseFailedExpectLine(message, *pos, kLineTypeOrigin, std::string(),
2151                                  error);
2152   }
2153   std::vector<std::string> fields;
2154   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
2155   const size_t expected_fields = 6;
2156   if (fields.size() != expected_fields) {
2157     return ParseFailedExpectFieldNum(line, expected_fields, error);
2158   }
2159   *session_id = fields[1];
2160   *session_version = fields[2];
2161 
2162   // RFC 4566
2163   // s=  (session name)
2164   if (!GetLineWithType(message, pos, &line, kLineTypeSessionName)) {
2165     return ParseFailedExpectLine(message, *pos, kLineTypeSessionName,
2166                                  std::string(), error);
2167   }
2168 
2169   // absl::optional lines
2170   // Those are the optional lines, so shouldn't return false if not present.
2171   // RFC 4566
2172   // i=* (session information)
2173   GetLineWithType(message, pos, &line, kLineTypeSessionInfo);
2174 
2175   // RFC 4566
2176   // u=* (URI of description)
2177   GetLineWithType(message, pos, &line, kLineTypeSessionUri);
2178 
2179   // RFC 4566
2180   // e=* (email address)
2181   GetLineWithType(message, pos, &line, kLineTypeSessionEmail);
2182 
2183   // RFC 4566
2184   // p=* (phone number)
2185   GetLineWithType(message, pos, &line, kLineTypeSessionPhone);
2186 
2187   // RFC 4566
2188   // c=* (connection information -- not required if included in
2189   //      all media)
2190   if (GetLineWithType(message, pos, &line, kLineTypeConnection)) {
2191     if (!ParseConnectionData(line, connection_addr, error)) {
2192       return false;
2193     }
2194   }
2195 
2196   // RFC 4566
2197   // b=* (zero or more bandwidth information lines)
2198   while (GetLineWithType(message, pos, &line, kLineTypeSessionBandwidth)) {
2199     // By pass zero or more b lines.
2200   }
2201 
2202   // RFC 4566
2203   // One or more time descriptions ("t=" and "r=" lines; see below)
2204   // t=  (time the session is active)
2205   // r=* (zero or more repeat times)
2206   // Ensure there's at least one time description
2207   if (!GetLineWithType(message, pos, &line, kLineTypeTiming)) {
2208     return ParseFailedExpectLine(message, *pos, kLineTypeTiming, std::string(),
2209                                  error);
2210   }
2211 
2212   while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
2213     // By pass zero or more r lines.
2214   }
2215 
2216   // Go through the rest of the time descriptions
2217   while (GetLineWithType(message, pos, &line, kLineTypeTiming)) {
2218     while (GetLineWithType(message, pos, &line, kLineTypeRepeatTimes)) {
2219       // By pass zero or more r lines.
2220     }
2221   }
2222 
2223   // RFC 4566
2224   // z=* (time zone adjustments)
2225   GetLineWithType(message, pos, &line, kLineTypeTimeZone);
2226 
2227   // RFC 4566
2228   // k=* (encryption key)
2229   GetLineWithType(message, pos, &line, kLineTypeEncryptionKey);
2230 
2231   // RFC 4566
2232   // a=* (zero or more session attribute lines)
2233   while (GetLineWithType(message, pos, &line, kLineTypeAttributes)) {
2234     if (HasAttribute(line, kAttributeGroup)) {
2235       if (!ParseGroupAttribute(line, desc, error)) {
2236         return false;
2237       }
2238     } else if (HasAttribute(line, kAttributeIceUfrag)) {
2239       if (!GetValue(line, kAttributeIceUfrag, &(session_td->ice_ufrag),
2240                     error)) {
2241         return false;
2242       }
2243     } else if (HasAttribute(line, kAttributeIcePwd)) {
2244       if (!GetValue(line, kAttributeIcePwd, &(session_td->ice_pwd), error)) {
2245         return false;
2246       }
2247     } else if (HasAttribute(line, kAttributeIceLite)) {
2248       session_td->ice_mode = cricket::ICEMODE_LITE;
2249     } else if (HasAttribute(line, kAttributeIceOption)) {
2250       if (!ParseIceOptions(line, &(session_td->transport_options), error)) {
2251         return false;
2252       }
2253     } else if (HasAttribute(line, kAttributeFingerprint)) {
2254       if (session_td->identity_fingerprint.get()) {
2255         return ParseFailed(
2256             line,
2257             "Can't have multiple fingerprint attributes at the same level.",
2258             error);
2259       }
2260       std::unique_ptr<rtc::SSLFingerprint> fingerprint;
2261       if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
2262         return false;
2263       }
2264       session_td->identity_fingerprint = std::move(fingerprint);
2265     } else if (HasAttribute(line, kAttributeSetup)) {
2266       if (!ParseDtlsSetup(line, &(session_td->connection_role), error)) {
2267         return false;
2268       }
2269     } else if (HasAttribute(line, kAttributeMsidSemantics)) {
2270       std::string semantics;
2271       if (!GetValue(line, kAttributeMsidSemantics, &semantics, error)) {
2272         return false;
2273       }
2274       desc->set_msid_supported(
2275           CaseInsensitiveFind(semantics, kMediaStreamSemantic));
2276     } else if (HasAttribute(line, kAttributeExtmapAllowMixed)) {
2277       desc->set_extmap_allow_mixed(true);
2278     } else if (HasAttribute(line, kAttributeExtmap)) {
2279       RtpExtension extmap;
2280       if (!ParseExtmap(line, &extmap, error)) {
2281         return false;
2282       }
2283       session_extmaps->push_back(extmap);
2284     }
2285   }
2286 
2287   return true;
2288 }
2289 
ParseGroupAttribute(const std::string & line,cricket::SessionDescription * desc,SdpParseError * error)2290 bool ParseGroupAttribute(const std::string& line,
2291                          cricket::SessionDescription* desc,
2292                          SdpParseError* error) {
2293   RTC_DCHECK(desc != NULL);
2294 
2295   // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
2296   // a=group:BUNDLE video voice
2297   std::vector<std::string> fields;
2298   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
2299   std::string semantics;
2300   if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
2301     return false;
2302   }
2303   cricket::ContentGroup group(semantics);
2304   for (size_t i = 1; i < fields.size(); ++i) {
2305     group.AddContentName(fields[i]);
2306   }
2307   desc->AddGroup(group);
2308   return true;
2309 }
2310 
ParseFingerprintAttribute(const std::string & line,std::unique_ptr<rtc::SSLFingerprint> * fingerprint,SdpParseError * error)2311 static bool ParseFingerprintAttribute(
2312     const std::string& line,
2313     std::unique_ptr<rtc::SSLFingerprint>* fingerprint,
2314     SdpParseError* error) {
2315   std::vector<std::string> fields;
2316   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
2317   const size_t expected_fields = 2;
2318   if (fields.size() != expected_fields) {
2319     return ParseFailedExpectFieldNum(line, expected_fields, error);
2320   }
2321 
2322   // The first field here is "fingerprint:<hash>.
2323   std::string algorithm;
2324   if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) {
2325     return false;
2326   }
2327 
2328   // Downcase the algorithm. Note that we don't need to downcase the
2329   // fingerprint because hex_decode can handle upper-case.
2330   absl::c_transform(algorithm, algorithm.begin(), ::tolower);
2331 
2332   // The second field is the digest value. De-hexify it.
2333   *fingerprint =
2334       rtc::SSLFingerprint::CreateUniqueFromRfc4572(algorithm, fields[1]);
2335   if (!*fingerprint) {
2336     return ParseFailed(line, "Failed to create fingerprint from the digest.",
2337                        error);
2338   }
2339 
2340   return true;
2341 }
2342 
ParseDtlsSetup(const std::string & line,cricket::ConnectionRole * role,SdpParseError * error)2343 static bool ParseDtlsSetup(const std::string& line,
2344                            cricket::ConnectionRole* role,
2345                            SdpParseError* error) {
2346   // setup-attr           =  "a=setup:" role
2347   // role                 =  "active" / "passive" / "actpass" / "holdconn"
2348   std::vector<std::string> fields;
2349   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColonChar, &fields);
2350   const size_t expected_fields = 2;
2351   if (fields.size() != expected_fields) {
2352     return ParseFailedExpectFieldNum(line, expected_fields, error);
2353   }
2354   std::string role_str = fields[1];
2355   if (!cricket::StringToConnectionRole(role_str, role)) {
2356     return ParseFailed(line, "Invalid attribute value.", error);
2357   }
2358   return true;
2359 }
2360 
ParseMsidAttribute(const std::string & line,std::vector<std::string> * stream_ids,std::string * track_id,SdpParseError * error)2361 static bool ParseMsidAttribute(const std::string& line,
2362                                std::vector<std::string>* stream_ids,
2363                                std::string* track_id,
2364                                SdpParseError* error) {
2365   // https://datatracker.ietf.org/doc/draft-ietf-mmusic-msid/16/
2366   // a=msid:<stream id> <track id>
2367   // msid-value = msid-id [ SP msid-appdata ]
2368   // msid-id = 1*64token-char ; see RFC 4566
2369   // msid-appdata = 1*64token-char  ; see RFC 4566
2370   std::string field1;
2371   std::string new_stream_id;
2372   std::string new_track_id;
2373   if (!rtc::tokenize_first(line.substr(kLinePrefixLength),
2374                            kSdpDelimiterSpaceChar, &field1, &new_track_id)) {
2375     const size_t expected_fields = 2;
2376     return ParseFailedExpectFieldNum(line, expected_fields, error);
2377   }
2378 
2379   if (new_track_id.empty()) {
2380     return ParseFailed(line, "Missing track ID in msid attribute.", error);
2381   }
2382   // All track ids should be the same within an m section in a Unified Plan SDP.
2383   if (!track_id->empty() && new_track_id.compare(*track_id) != 0) {
2384     return ParseFailed(
2385         line, "Two different track IDs in msid attribute in one m= section",
2386         error);
2387   }
2388   *track_id = new_track_id;
2389 
2390   // msid:<msid-id>
2391   if (!GetValue(field1, kAttributeMsid, &new_stream_id, error)) {
2392     return false;
2393   }
2394   if (new_stream_id.empty()) {
2395     return ParseFailed(line, "Missing stream ID in msid attribute.", error);
2396   }
2397   // The special value "-" indicates "no MediaStream".
2398   if (new_stream_id.compare(kNoStreamMsid) != 0) {
2399     stream_ids->push_back(new_stream_id);
2400   }
2401   return true;
2402 }
2403 
RemoveInvalidRidDescriptions(const std::vector<int> & payload_types,std::vector<RidDescription> * rids)2404 static void RemoveInvalidRidDescriptions(const std::vector<int>& payload_types,
2405                                          std::vector<RidDescription>* rids) {
2406   RTC_DCHECK(rids);
2407   std::set<std::string> to_remove;
2408   std::set<std::string> unique_rids;
2409 
2410   // Check the rids to see which ones should be removed.
2411   for (RidDescription& rid : *rids) {
2412     // In the case of a duplicate, the entire "a=rid" line, and all "a=rid"
2413     // lines with rid-ids that duplicate this line, are discarded and MUST NOT
2414     // be included in the SDP Answer.
2415     auto pair = unique_rids.insert(rid.rid);
2416     // Insert will "fail" if element already exists.
2417     if (!pair.second) {
2418       to_remove.insert(rid.rid);
2419       continue;
2420     }
2421 
2422     // If the "a=rid" line contains a "pt=", the list of payload types
2423     // is verified against the list of valid payload types for the media
2424     // section (that is, those listed on the "m=" line).  Any PT missing
2425     // from the "m=" line is discarded from the set of values in the
2426     // "pt=".  If no values are left in the "pt=" parameter after this
2427     // processing, then the "a=rid" line is discarded.
2428     if (rid.payload_types.empty()) {
2429       // If formats were not specified, rid should not be removed.
2430       continue;
2431     }
2432 
2433     // Note: Spec does not mention how to handle duplicate formats.
2434     // Media section does not handle duplicates either.
2435     std::set<int> removed_formats;
2436     for (int payload_type : rid.payload_types) {
2437       if (!absl::c_linear_search(payload_types, payload_type)) {
2438         removed_formats.insert(payload_type);
2439       }
2440     }
2441 
2442     rid.payload_types.erase(
2443         std::remove_if(rid.payload_types.begin(), rid.payload_types.end(),
2444                        [&removed_formats](int format) {
2445                          return removed_formats.count(format) > 0;
2446                        }),
2447         rid.payload_types.end());
2448 
2449     // If all formats were removed then remove the rid alogether.
2450     if (rid.payload_types.empty()) {
2451       to_remove.insert(rid.rid);
2452     }
2453   }
2454 
2455   // Remove every rid description that appears in the to_remove list.
2456   if (!to_remove.empty()) {
2457     rids->erase(std::remove_if(rids->begin(), rids->end(),
2458                                [&to_remove](const RidDescription& rid) {
2459                                  return to_remove.count(rid.rid) > 0;
2460                                }),
2461                 rids->end());
2462   }
2463 }
2464 
2465 // Create a new list (because SimulcastLayerList is immutable) without any
2466 // layers that have a rid in the to_remove list.
2467 // If a group of alternatives is empty after removing layers, the group should
2468 // be removed altogether.
RemoveRidsFromSimulcastLayerList(const std::set<std::string> & to_remove,const SimulcastLayerList & layers)2469 static SimulcastLayerList RemoveRidsFromSimulcastLayerList(
2470     const std::set<std::string>& to_remove,
2471     const SimulcastLayerList& layers) {
2472   SimulcastLayerList result;
2473   for (const std::vector<SimulcastLayer>& vector : layers) {
2474     std::vector<SimulcastLayer> new_layers;
2475     for (const SimulcastLayer& layer : vector) {
2476       if (to_remove.find(layer.rid) == to_remove.end()) {
2477         new_layers.push_back(layer);
2478       }
2479     }
2480     // If all layers were removed, do not add an entry.
2481     if (!new_layers.empty()) {
2482       result.AddLayerWithAlternatives(new_layers);
2483     }
2484   }
2485 
2486   return result;
2487 }
2488 
2489 // Will remove Simulcast Layers if:
2490 // 1. They appear in both send and receive directions.
2491 // 2. They do not appear in the list of |valid_rids|.
RemoveInvalidRidsFromSimulcast(const std::vector<RidDescription> & valid_rids,SimulcastDescription * simulcast)2492 static void RemoveInvalidRidsFromSimulcast(
2493     const std::vector<RidDescription>& valid_rids,
2494     SimulcastDescription* simulcast) {
2495   RTC_DCHECK(simulcast);
2496   std::set<std::string> to_remove;
2497   std::vector<SimulcastLayer> all_send_layers =
2498       simulcast->send_layers().GetAllLayers();
2499   std::vector<SimulcastLayer> all_receive_layers =
2500       simulcast->receive_layers().GetAllLayers();
2501 
2502   // If a rid appears in both send and receive directions, remove it from both.
2503   // This algorithm runs in O(n^2) time, but for small n (as is the case with
2504   // simulcast layers) it should still perform well.
2505   for (const SimulcastLayer& send_layer : all_send_layers) {
2506     if (absl::c_any_of(all_receive_layers,
2507                        [&send_layer](const SimulcastLayer& layer) {
2508                          return layer.rid == send_layer.rid;
2509                        })) {
2510       to_remove.insert(send_layer.rid);
2511     }
2512   }
2513 
2514   // Add any rid that is not in the valid list to the remove set.
2515   for (const SimulcastLayer& send_layer : all_send_layers) {
2516     if (absl::c_none_of(valid_rids, [&send_layer](const RidDescription& rid) {
2517           return send_layer.rid == rid.rid &&
2518                  rid.direction == cricket::RidDirection::kSend;
2519         })) {
2520       to_remove.insert(send_layer.rid);
2521     }
2522   }
2523 
2524   // Add any rid that is not in the valid list to the remove set.
2525   for (const SimulcastLayer& receive_layer : all_receive_layers) {
2526     if (absl::c_none_of(
2527             valid_rids, [&receive_layer](const RidDescription& rid) {
2528               return receive_layer.rid == rid.rid &&
2529                      rid.direction == cricket::RidDirection::kReceive;
2530             })) {
2531       to_remove.insert(receive_layer.rid);
2532     }
2533   }
2534 
2535   simulcast->send_layers() =
2536       RemoveRidsFromSimulcastLayerList(to_remove, simulcast->send_layers());
2537   simulcast->receive_layers() =
2538       RemoveRidsFromSimulcastLayerList(to_remove, simulcast->receive_layers());
2539 }
2540 
2541 // RFC 3551
2542 //  PT   encoding    media type  clock rate   channels
2543 //                      name                    (Hz)
2544 //  0    PCMU        A            8,000       1
2545 //  1    reserved    A
2546 //  2    reserved    A
2547 //  3    GSM         A            8,000       1
2548 //  4    G723        A            8,000       1
2549 //  5    DVI4        A            8,000       1
2550 //  6    DVI4        A           16,000       1
2551 //  7    LPC         A            8,000       1
2552 //  8    PCMA        A            8,000       1
2553 //  9    G722        A            8,000       1
2554 //  10   L16         A           44,100       2
2555 //  11   L16         A           44,100       1
2556 //  12   QCELP       A            8,000       1
2557 //  13   CN          A            8,000       1
2558 //  14   MPA         A           90,000       (see text)
2559 //  15   G728        A            8,000       1
2560 //  16   DVI4        A           11,025       1
2561 //  17   DVI4        A           22,050       1
2562 //  18   G729        A            8,000       1
2563 struct StaticPayloadAudioCodec {
2564   const char* name;
2565   int clockrate;
2566   size_t channels;
2567 };
2568 static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = {
2569     {"PCMU", 8000, 1},  {"reserved", 0, 0}, {"reserved", 0, 0},
2570     {"GSM", 8000, 1},   {"G723", 8000, 1},  {"DVI4", 8000, 1},
2571     {"DVI4", 16000, 1}, {"LPC", 8000, 1},   {"PCMA", 8000, 1},
2572     {"G722", 8000, 1},  {"L16", 44100, 2},  {"L16", 44100, 1},
2573     {"QCELP", 8000, 1}, {"CN", 8000, 1},    {"MPA", 90000, 1},
2574     {"G728", 8000, 1},  {"DVI4", 11025, 1}, {"DVI4", 22050, 1},
2575     {"G729", 8000, 1},
2576 };
2577 
MaybeCreateStaticPayloadAudioCodecs(const std::vector<int> & fmts,AudioContentDescription * media_desc)2578 void MaybeCreateStaticPayloadAudioCodecs(const std::vector<int>& fmts,
2579                                          AudioContentDescription* media_desc) {
2580   if (!media_desc) {
2581     return;
2582   }
2583   RTC_DCHECK(media_desc->codecs().empty());
2584   for (int payload_type : fmts) {
2585     if (!media_desc->HasCodec(payload_type) && payload_type >= 0 &&
2586         static_cast<uint32_t>(payload_type) <
2587             arraysize(kStaticPayloadAudioCodecs)) {
2588       std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name;
2589       int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate;
2590       size_t channels = kStaticPayloadAudioCodecs[payload_type].channels;
2591       media_desc->AddCodec(cricket::AudioCodec(payload_type, encoding_name,
2592                                                clock_rate, 0, channels));
2593     }
2594   }
2595 }
2596 
2597 template <class C>
ParseContentDescription(const std::string & message,const cricket::MediaType media_type,int mline_index,const std::string & protocol,const std::vector<int> & payload_types,size_t * pos,std::string * content_name,bool * bundle_only,int * msid_signaling,TransportDescription * transport,std::vector<std::unique_ptr<JsepIceCandidate>> * candidates,webrtc::SdpParseError * error)2598 static std::unique_ptr<C> ParseContentDescription(
2599     const std::string& message,
2600     const cricket::MediaType media_type,
2601     int mline_index,
2602     const std::string& protocol,
2603     const std::vector<int>& payload_types,
2604     size_t* pos,
2605     std::string* content_name,
2606     bool* bundle_only,
2607     int* msid_signaling,
2608     TransportDescription* transport,
2609     std::vector<std::unique_ptr<JsepIceCandidate>>* candidates,
2610     webrtc::SdpParseError* error) {
2611   auto media_desc = std::make_unique<C>();
2612   media_desc->set_extmap_allow_mixed_enum(MediaContentDescription::kNo);
2613   if (!ParseContent(message, media_type, mline_index, protocol, payload_types,
2614                     pos, content_name, bundle_only, msid_signaling,
2615                     media_desc.get(), transport, candidates, error)) {
2616     return nullptr;
2617   }
2618   // Sort the codecs according to the m-line fmt list.
2619   std::unordered_map<int, int> payload_type_preferences;
2620   // "size + 1" so that the lowest preference payload type has a preference of
2621   // 1, which is greater than the default (0) for payload types not in the fmt
2622   // list.
2623   int preference = static_cast<int>(payload_types.size() + 1);
2624   for (int pt : payload_types) {
2625     payload_type_preferences[pt] = preference--;
2626   }
2627   std::vector<typename C::CodecType> codecs = media_desc->codecs();
2628   absl::c_sort(
2629       codecs, [&payload_type_preferences](const typename C::CodecType& a,
2630                                           const typename C::CodecType& b) {
2631         return payload_type_preferences[a.id] > payload_type_preferences[b.id];
2632       });
2633   media_desc->set_codecs(codecs);
2634   return media_desc;
2635 }
2636 
ParseMediaDescription(const std::string & message,const TransportDescription & session_td,const RtpHeaderExtensions & session_extmaps,size_t * pos,const rtc::SocketAddress & session_connection_addr,cricket::SessionDescription * desc,std::vector<std::unique_ptr<JsepIceCandidate>> * candidates,SdpParseError * error)2637 bool ParseMediaDescription(
2638     const std::string& message,
2639     const TransportDescription& session_td,
2640     const RtpHeaderExtensions& session_extmaps,
2641     size_t* pos,
2642     const rtc::SocketAddress& session_connection_addr,
2643     cricket::SessionDescription* desc,
2644     std::vector<std::unique_ptr<JsepIceCandidate>>* candidates,
2645     SdpParseError* error) {
2646   RTC_DCHECK(desc != NULL);
2647   std::string line;
2648   int mline_index = -1;
2649   int msid_signaling = 0;
2650 
2651   // Zero or more media descriptions
2652   // RFC 4566
2653   // m=<media> <port> <proto> <fmt>
2654   while (GetLineWithType(message, pos, &line, kLineTypeMedia)) {
2655     ++mline_index;
2656 
2657     std::vector<std::string> fields;
2658     rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
2659 
2660     const size_t expected_min_fields = 4;
2661     if (fields.size() < expected_min_fields) {
2662       return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
2663     }
2664     bool port_rejected = false;
2665     // RFC 3264
2666     // To reject an offered stream, the port number in the corresponding stream
2667     // in the answer MUST be set to zero.
2668     if (fields[1] == kMediaPortRejected) {
2669       port_rejected = true;
2670     }
2671 
2672     int port = 0;
2673     if (!rtc::FromString<int>(fields[1], &port) || !IsValidPort(port)) {
2674       return ParseFailed(line, "The port number is invalid", error);
2675     }
2676     const std::string& protocol = fields[2];
2677 
2678     // <fmt>
2679     std::vector<int> payload_types;
2680     if (cricket::IsRtpProtocol(protocol)) {
2681       for (size_t j = 3; j < fields.size(); ++j) {
2682         int pl = 0;
2683         if (!GetPayloadTypeFromString(line, fields[j], &pl, error)) {
2684           return false;
2685         }
2686         payload_types.push_back(pl);
2687       }
2688     }
2689 
2690     // Make a temporary TransportDescription based on |session_td|.
2691     // Some of this gets overwritten by ParseContent.
2692     TransportDescription transport(
2693         session_td.transport_options, session_td.ice_ufrag, session_td.ice_pwd,
2694         session_td.ice_mode, session_td.connection_role,
2695         session_td.identity_fingerprint.get());
2696 
2697     std::unique_ptr<MediaContentDescription> content;
2698     std::string content_name;
2699     bool bundle_only = false;
2700     int section_msid_signaling = 0;
2701     const std::string& media_type = fields[0];
2702     if ((media_type == kMediaTypeVideo || media_type == kMediaTypeAudio) &&
2703         !cricket::IsRtpProtocol(protocol)) {
2704       return ParseFailed(line, "Unsupported protocol for media type", error);
2705     }
2706     if (media_type == kMediaTypeVideo) {
2707       content = ParseContentDescription<VideoContentDescription>(
2708           message, cricket::MEDIA_TYPE_VIDEO, mline_index, protocol,
2709           payload_types, pos, &content_name, &bundle_only,
2710           &section_msid_signaling, &transport, candidates, error);
2711     } else if (media_type == kMediaTypeAudio) {
2712       content = ParseContentDescription<AudioContentDescription>(
2713           message, cricket::MEDIA_TYPE_AUDIO, mline_index, protocol,
2714           payload_types, pos, &content_name, &bundle_only,
2715           &section_msid_signaling, &transport, candidates, error);
2716     } else if (media_type == kMediaTypeData) {
2717       if (cricket::IsDtlsSctp(protocol)) {
2718         // The draft-03 format is:
2719         // m=application <port> DTLS/SCTP <sctp-port>...
2720         // use_sctpmap should be false.
2721         // The draft-26 format is:
2722         // m=application <port> UDP/DTLS/SCTP webrtc-datachannel
2723         // use_sctpmap should be false.
2724         auto data_desc = std::make_unique<SctpDataContentDescription>();
2725         // Default max message size is 64K
2726         // according to draft-ietf-mmusic-sctp-sdp-26
2727         data_desc->set_max_message_size(kDefaultSctpMaxMessageSize);
2728         int p;
2729         if (rtc::FromString(fields[3], &p)) {
2730           data_desc->set_port(p);
2731         } else if (fields[3] == kDefaultSctpmapProtocol) {
2732           data_desc->set_use_sctpmap(false);
2733         }
2734         if (!ParseContent(message, cricket::MEDIA_TYPE_DATA, mline_index,
2735                           protocol, payload_types, pos, &content_name,
2736                           &bundle_only, &section_msid_signaling,
2737                           data_desc.get(), &transport, candidates, error)) {
2738           return false;
2739         }
2740         data_desc->set_protocol(protocol);
2741         content = std::move(data_desc);
2742       } else if (cricket::IsRtpProtocol(protocol)) {
2743         // RTP
2744         std::unique_ptr<RtpDataContentDescription> data_desc =
2745             ParseContentDescription<RtpDataContentDescription>(
2746                 message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
2747                 payload_types, pos, &content_name, &bundle_only,
2748                 &section_msid_signaling, &transport, candidates, error);
2749         content = std::move(data_desc);
2750       } else {
2751         return ParseFailed(line, "Unsupported protocol for media type", error);
2752       }
2753     } else {
2754       RTC_LOG(LS_WARNING) << "Unsupported media type: " << line;
2755       auto unsupported_desc =
2756           std::make_unique<UnsupportedContentDescription>(media_type);
2757       if (!ParseContent(message, cricket::MEDIA_TYPE_UNSUPPORTED, mline_index,
2758                         protocol, payload_types, pos, &content_name,
2759                         &bundle_only, &section_msid_signaling,
2760                         unsupported_desc.get(), &transport, candidates,
2761                         error)) {
2762         return false;
2763       }
2764       unsupported_desc->set_protocol(protocol);
2765       content = std::move(unsupported_desc);
2766     }
2767     if (!content.get()) {
2768       // ParseContentDescription returns NULL if failed.
2769       return false;
2770     }
2771 
2772     msid_signaling |= section_msid_signaling;
2773 
2774     bool content_rejected = false;
2775     // A port of 0 is not interpreted as a rejected m= section when it's
2776     // used along with a=bundle-only.
2777     if (bundle_only) {
2778       if (!port_rejected) {
2779         // Usage of bundle-only with a nonzero port is unspecified. So just
2780         // ignore bundle-only if we see this.
2781         bundle_only = false;
2782         RTC_LOG(LS_WARNING)
2783             << "a=bundle-only attribute observed with a nonzero "
2784                "port; this usage is unspecified so the attribute is being "
2785                "ignored.";
2786       }
2787     } else {
2788       // If not using bundle-only, interpret port 0 in the normal way; the m=
2789       // section is being rejected.
2790       content_rejected = port_rejected;
2791     }
2792 
2793     if (content->as_unsupported()) {
2794       content_rejected = true;
2795     } else if (cricket::IsRtpProtocol(protocol) && !content->as_sctp()) {
2796       content->set_protocol(protocol);
2797       // Set the extmap.
2798       if (!session_extmaps.empty() &&
2799           !content->rtp_header_extensions().empty()) {
2800         return ParseFailed("",
2801                            "The a=extmap MUST be either all session level or "
2802                            "all media level.",
2803                            error);
2804       }
2805       for (size_t i = 0; i < session_extmaps.size(); ++i) {
2806         content->AddRtpHeaderExtension(session_extmaps[i]);
2807       }
2808     } else if (content->as_sctp()) {
2809       // Do nothing, it's OK
2810     } else {
2811       RTC_LOG(LS_WARNING) << "Parse failed with unknown protocol " << protocol;
2812       return false;
2813     }
2814 
2815     // Use the session level connection address if the media level addresses are
2816     // not specified.
2817     rtc::SocketAddress address;
2818     address = content->connection_address().IsNil()
2819                   ? session_connection_addr
2820                   : content->connection_address();
2821     address.SetPort(port);
2822     content->set_connection_address(address);
2823 
2824     desc->AddContent(content_name,
2825                      cricket::IsDtlsSctp(protocol) ? MediaProtocolType::kSctp
2826                                                    : MediaProtocolType::kRtp,
2827                      content_rejected, bundle_only, std::move(content));
2828     // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag".
2829     desc->AddTransportInfo(TransportInfo(content_name, transport));
2830   }
2831 
2832   desc->set_msid_signaling(msid_signaling);
2833 
2834   size_t end_of_message = message.size();
2835   if (mline_index == -1 && *pos != end_of_message) {
2836     ParseFailed(message, *pos, "Expects m line.", error);
2837     return false;
2838   }
2839   return true;
2840 }
2841 
VerifyCodec(const cricket::Codec & codec)2842 bool VerifyCodec(const cricket::Codec& codec) {
2843   // Codec has not been populated correctly unless the name has been set. This
2844   // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't
2845   // have a corresponding "rtpmap" line.
2846   return !codec.name.empty();
2847 }
2848 
VerifyAudioCodecs(const AudioContentDescription * audio_desc)2849 bool VerifyAudioCodecs(const AudioContentDescription* audio_desc) {
2850   return absl::c_all_of(audio_desc->codecs(), &VerifyCodec);
2851 }
2852 
VerifyVideoCodecs(const VideoContentDescription * video_desc)2853 bool VerifyVideoCodecs(const VideoContentDescription* video_desc) {
2854   return absl::c_all_of(video_desc->codecs(), &VerifyCodec);
2855 }
2856 
AddParameters(const cricket::CodecParameterMap & parameters,cricket::Codec * codec)2857 void AddParameters(const cricket::CodecParameterMap& parameters,
2858                    cricket::Codec* codec) {
2859   for (const auto& entry : parameters) {
2860     const std::string& key = entry.first;
2861     const std::string& value = entry.second;
2862     codec->SetParam(key, value);
2863   }
2864 }
2865 
AddFeedbackParameter(const cricket::FeedbackParam & feedback_param,cricket::Codec * codec)2866 void AddFeedbackParameter(const cricket::FeedbackParam& feedback_param,
2867                           cricket::Codec* codec) {
2868   codec->AddFeedbackParam(feedback_param);
2869 }
2870 
AddFeedbackParameters(const cricket::FeedbackParams & feedback_params,cricket::Codec * codec)2871 void AddFeedbackParameters(const cricket::FeedbackParams& feedback_params,
2872                            cricket::Codec* codec) {
2873   for (const cricket::FeedbackParam& param : feedback_params.params()) {
2874     codec->AddFeedbackParam(param);
2875   }
2876 }
2877 
2878 // Gets the current codec setting associated with |payload_type|. If there
2879 // is no Codec associated with that payload type it returns an empty codec
2880 // with that payload type.
2881 template <class T>
GetCodecWithPayloadType(const std::vector<T> & codecs,int payload_type)2882 T GetCodecWithPayloadType(const std::vector<T>& codecs, int payload_type) {
2883   const T* codec = FindCodecById(codecs, payload_type);
2884   if (codec)
2885     return *codec;
2886   // Return empty codec with |payload_type|.
2887   T ret_val;
2888   ret_val.id = payload_type;
2889   return ret_val;
2890 }
2891 
2892 // Updates or creates a new codec entry in the audio description.
2893 template <class T, class U>
AddOrReplaceCodec(MediaContentDescription * content_desc,const U & codec)2894 void AddOrReplaceCodec(MediaContentDescription* content_desc, const U& codec) {
2895   T* desc = static_cast<T*>(content_desc);
2896   std::vector<U> codecs = desc->codecs();
2897   bool found = false;
2898   for (U& existing_codec : codecs) {
2899     if (codec.id == existing_codec.id) {
2900       // Overwrite existing codec with the new codec.
2901       existing_codec = codec;
2902       found = true;
2903       break;
2904     }
2905   }
2906   if (!found) {
2907     desc->AddCodec(codec);
2908     return;
2909   }
2910   desc->set_codecs(codecs);
2911 }
2912 
2913 // Adds or updates existing codec corresponding to |payload_type| according
2914 // to |parameters|.
2915 template <class T, class U>
UpdateCodec(MediaContentDescription * content_desc,int payload_type,const cricket::CodecParameterMap & parameters)2916 void UpdateCodec(MediaContentDescription* content_desc,
2917                  int payload_type,
2918                  const cricket::CodecParameterMap& parameters) {
2919   // Codec might already have been populated (from rtpmap).
2920   U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2921                                         payload_type);
2922   AddParameters(parameters, &new_codec);
2923   AddOrReplaceCodec<T, U>(content_desc, new_codec);
2924 }
2925 
2926 // Adds or updates existing codec corresponding to |payload_type| according
2927 // to |feedback_param|.
2928 template <class T, class U>
UpdateCodec(MediaContentDescription * content_desc,int payload_type,const cricket::FeedbackParam & feedback_param)2929 void UpdateCodec(MediaContentDescription* content_desc,
2930                  int payload_type,
2931                  const cricket::FeedbackParam& feedback_param) {
2932   // Codec might already have been populated (from rtpmap).
2933   U new_codec = GetCodecWithPayloadType(static_cast<T*>(content_desc)->codecs(),
2934                                         payload_type);
2935   AddFeedbackParameter(feedback_param, &new_codec);
2936   AddOrReplaceCodec<T, U>(content_desc, new_codec);
2937 }
2938 
2939 // Adds or updates existing video codec corresponding to |payload_type|
2940 // according to |packetization|.
UpdateVideoCodecPacketization(VideoContentDescription * video_desc,int payload_type,const std::string & packetization)2941 void UpdateVideoCodecPacketization(VideoContentDescription* video_desc,
2942                                    int payload_type,
2943                                    const std::string& packetization) {
2944   if (packetization != cricket::kPacketizationParamRaw) {
2945     // Ignore unsupported packetization attribute.
2946     return;
2947   }
2948 
2949   // Codec might already have been populated (from rtpmap).
2950   cricket::VideoCodec codec =
2951       GetCodecWithPayloadType(video_desc->codecs(), payload_type);
2952   codec.packetization = packetization;
2953   AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
2954                                                                   codec);
2955 }
2956 
2957 template <class T>
PopWildcardCodec(std::vector<T> * codecs,T * wildcard_codec)2958 bool PopWildcardCodec(std::vector<T>* codecs, T* wildcard_codec) {
2959   for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) {
2960     if (iter->id == kWildcardPayloadType) {
2961       *wildcard_codec = *iter;
2962       codecs->erase(iter);
2963       return true;
2964     }
2965   }
2966   return false;
2967 }
2968 
2969 template <class T>
UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T> * desc)2970 void UpdateFromWildcardCodecs(cricket::MediaContentDescriptionImpl<T>* desc) {
2971   auto codecs = desc->codecs();
2972   T wildcard_codec;
2973   if (!PopWildcardCodec(&codecs, &wildcard_codec)) {
2974     return;
2975   }
2976   for (auto& codec : codecs) {
2977     AddFeedbackParameters(wildcard_codec.feedback_params, &codec);
2978   }
2979   desc->set_codecs(codecs);
2980 }
2981 
AddAudioAttribute(const std::string & name,const std::string & value,AudioContentDescription * audio_desc)2982 void AddAudioAttribute(const std::string& name,
2983                        const std::string& value,
2984                        AudioContentDescription* audio_desc) {
2985   if (value.empty()) {
2986     return;
2987   }
2988   std::vector<cricket::AudioCodec> codecs = audio_desc->codecs();
2989   for (cricket::AudioCodec& codec : codecs) {
2990     codec.params[name] = value;
2991   }
2992   audio_desc->set_codecs(codecs);
2993 }
2994 
ParseContent(const std::string & message,const cricket::MediaType media_type,int mline_index,const std::string & protocol,const std::vector<int> & payload_types,size_t * pos,std::string * content_name,bool * bundle_only,int * msid_signaling,MediaContentDescription * media_desc,TransportDescription * transport,std::vector<std::unique_ptr<JsepIceCandidate>> * candidates,SdpParseError * error)2995 bool ParseContent(const std::string& message,
2996                   const cricket::MediaType media_type,
2997                   int mline_index,
2998                   const std::string& protocol,
2999                   const std::vector<int>& payload_types,
3000                   size_t* pos,
3001                   std::string* content_name,
3002                   bool* bundle_only,
3003                   int* msid_signaling,
3004                   MediaContentDescription* media_desc,
3005                   TransportDescription* transport,
3006                   std::vector<std::unique_ptr<JsepIceCandidate>>* candidates,
3007                   SdpParseError* error) {
3008   RTC_DCHECK(media_desc != NULL);
3009   RTC_DCHECK(content_name != NULL);
3010   RTC_DCHECK(transport != NULL);
3011 
3012   if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3013     MaybeCreateStaticPayloadAudioCodecs(payload_types, media_desc->as_audio());
3014   }
3015 
3016   // The media level "ice-ufrag" and "ice-pwd".
3017   // The candidates before update the media level "ice-pwd" and "ice-ufrag".
3018   Candidates candidates_orig;
3019   std::string line;
3020   std::string mline_id;
3021   // Tracks created out of the ssrc attributes.
3022   StreamParamsVec tracks;
3023   SsrcInfoVec ssrc_infos;
3024   SsrcGroupVec ssrc_groups;
3025   std::string maxptime_as_string;
3026   std::string ptime_as_string;
3027   std::vector<std::string> stream_ids;
3028   std::string track_id;
3029   SdpSerializer deserializer;
3030   std::vector<RidDescription> rids;
3031   SimulcastDescription simulcast;
3032 
3033   // Loop until the next m line
3034   while (!IsLineType(message, kLineTypeMedia, *pos)) {
3035     if (!GetLine(message, pos, &line)) {
3036       if (*pos >= message.size()) {
3037         break;  // Done parsing
3038       } else {
3039         return ParseFailed(message, *pos, "Invalid SDP line.", error);
3040       }
3041     }
3042 
3043     // RFC 4566
3044     // b=* (zero or more bandwidth information lines)
3045     if (IsLineType(line, kLineTypeSessionBandwidth)) {
3046       std::string bandwidth;
3047       std::string bandwidth_type;
3048       if (!rtc::tokenize_first(line.substr(kLinePrefixLength),
3049                                kSdpDelimiterColonChar, &bandwidth_type,
3050                                &bandwidth)) {
3051         return ParseFailed(
3052             line,
3053             "b= syntax error, does not match b=<modifier>:<bandwidth-value>.",
3054             error);
3055       }
3056       if (!(bandwidth_type == kApplicationSpecificBandwidth ||
3057             bandwidth_type == kTransportSpecificBandwidth)) {
3058         // Ignore unknown bandwidth types.
3059         continue;
3060       }
3061       int b = 0;
3062       if (!GetValueFromString(line, bandwidth, &b, error)) {
3063         return false;
3064       }
3065       // TODO(deadbeef): Historically, applications may be setting a value
3066       // of -1 to mean "unset any previously set bandwidth limit", even
3067       // though ommitting the "b=AS" entirely will do just that. Once we've
3068       // transitioned applications to doing the right thing, it would be
3069       // better to treat this as a hard error instead of just ignoring it.
3070       if (bandwidth_type == kApplicationSpecificBandwidth && b == -1) {
3071         RTC_LOG(LS_WARNING) << "Ignoring \"b=AS:-1\"; will be treated as \"no "
3072                                "bandwidth limit\".";
3073         continue;
3074       }
3075       if (b < 0) {
3076         return ParseFailed(
3077             line, "b=" + bandwidth_type + " value can't be negative.", error);
3078       }
3079       // We should never use more than the default bandwidth for RTP-based
3080       // data channels. Don't allow SDP to set the bandwidth, because
3081       // that would give JS the opportunity to "break the Internet".
3082       // See: https://code.google.com/p/chromium/issues/detail?id=280726
3083       // Disallow TIAS since it shouldn't be generated for RTP data channels in
3084       // the first place and provides another way to get around the limitation.
3085       if (media_type == cricket::MEDIA_TYPE_DATA &&
3086           cricket::IsRtpProtocol(protocol) &&
3087           (b > cricket::kRtpDataMaxBandwidth / 1000 ||
3088            bandwidth_type == kTransportSpecificBandwidth)) {
3089         rtc::StringBuilder description;
3090         description << "RTP-based data channels may not send more than "
3091                     << cricket::kRtpDataMaxBandwidth / 1000 << "kbps.";
3092         return ParseFailed(line, description.str(), error);
3093       }
3094       // Convert values. Prevent integer overflow.
3095       if (bandwidth_type == kApplicationSpecificBandwidth) {
3096         b = std::min(b, INT_MAX / 1000) * 1000;
3097       } else {
3098         b = std::min(b, INT_MAX);
3099       }
3100       media_desc->set_bandwidth(b);
3101       media_desc->set_bandwidth_type(bandwidth_type);
3102       continue;
3103     }
3104 
3105     // Parse the media level connection data.
3106     if (IsLineType(line, kLineTypeConnection)) {
3107       rtc::SocketAddress addr;
3108       if (!ParseConnectionData(line, &addr, error)) {
3109         return false;
3110       }
3111       media_desc->set_connection_address(addr);
3112       continue;
3113     }
3114 
3115     if (!IsLineType(line, kLineTypeAttributes)) {
3116       // TODO(deadbeef): Handle other lines if needed.
3117       RTC_LOG(LS_VERBOSE) << "Ignored line: " << line;
3118       continue;
3119     }
3120 
3121     // Handle attributes common to SCTP and RTP.
3122     if (HasAttribute(line, kAttributeMid)) {
3123       // RFC 3388
3124       // mid-attribute      = "a=mid:" identification-tag
3125       // identification-tag = token
3126       // Use the mid identification-tag as the content name.
3127       if (!GetSingleTokenValue(line, kAttributeMid, &mline_id, error)) {
3128         return false;
3129       }
3130       *content_name = mline_id;
3131     } else if (HasAttribute(line, kAttributeBundleOnly)) {
3132       *bundle_only = true;
3133     } else if (HasAttribute(line, kAttributeCandidate)) {
3134       Candidate candidate;
3135       if (!ParseCandidate(line, &candidate, error, false)) {
3136         return false;
3137       }
3138       // ParseCandidate will parse non-standard ufrag and password attributes,
3139       // since it's used for candidate trickling, but we only want to process
3140       // the "a=ice-ufrag"/"a=ice-pwd" values in a session description, so
3141       // strip them off at this point.
3142       candidate.set_username(std::string());
3143       candidate.set_password(std::string());
3144       candidates_orig.push_back(candidate);
3145     } else if (HasAttribute(line, kAttributeIceUfrag)) {
3146       if (!GetValue(line, kAttributeIceUfrag, &transport->ice_ufrag, error)) {
3147         return false;
3148       }
3149     } else if (HasAttribute(line, kAttributeIcePwd)) {
3150       if (!GetValue(line, kAttributeIcePwd, &transport->ice_pwd, error)) {
3151         return false;
3152       }
3153     } else if (HasAttribute(line, kAttributeIceOption)) {
3154       if (!ParseIceOptions(line, &transport->transport_options, error)) {
3155         return false;
3156       }
3157     } else if (HasAttribute(line, kAttributeFmtp)) {
3158       if (!ParseFmtpAttributes(line, media_type, media_desc, error)) {
3159         return false;
3160       }
3161     } else if (HasAttribute(line, kAttributeFingerprint)) {
3162       std::unique_ptr<rtc::SSLFingerprint> fingerprint;
3163       if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
3164         return false;
3165       }
3166       transport->identity_fingerprint = std::move(fingerprint);
3167     } else if (HasAttribute(line, kAttributeSetup)) {
3168       if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
3169         return false;
3170       }
3171     } else if (cricket::IsDtlsSctp(protocol) &&
3172                media_type == cricket::MEDIA_TYPE_DATA) {
3173       //
3174       // SCTP specific attributes
3175       //
3176       if (HasAttribute(line, kAttributeSctpPort)) {
3177         if (media_desc->as_sctp()->use_sctpmap()) {
3178           return ParseFailed(
3179               line, "sctp-port attribute can't be used with sctpmap.", error);
3180         }
3181         int sctp_port;
3182         if (!ParseSctpPort(line, &sctp_port, error)) {
3183           return false;
3184         }
3185         media_desc->as_sctp()->set_port(sctp_port);
3186       } else if (HasAttribute(line, kAttributeMaxMessageSize)) {
3187         int max_message_size;
3188         if (!ParseSctpMaxMessageSize(line, &max_message_size, error)) {
3189           return false;
3190         }
3191         media_desc->as_sctp()->set_max_message_size(max_message_size);
3192       } else if (HasAttribute(line, kAttributeSctpmap)) {
3193         // Ignore a=sctpmap: from early versions of draft-ietf-mmusic-sctp-sdp
3194         continue;
3195       }
3196     } else if (cricket::IsRtpProtocol(protocol)) {
3197       //
3198       // RTP specific attributes
3199       //
3200       if (HasAttribute(line, kAttributeRtcpMux)) {
3201         media_desc->set_rtcp_mux(true);
3202       } else if (HasAttribute(line, kAttributeRtcpReducedSize)) {
3203         media_desc->set_rtcp_reduced_size(true);
3204       } else if (HasAttribute(line, kAttributeRtcpRemoteEstimate)) {
3205         media_desc->set_remote_estimate(true);
3206       } else if (HasAttribute(line, kAttributeSsrcGroup)) {
3207         if (!ParseSsrcGroupAttribute(line, &ssrc_groups, error)) {
3208           return false;
3209         }
3210       } else if (HasAttribute(line, kAttributeSsrc)) {
3211         if (!ParseSsrcAttribute(line, &ssrc_infos, msid_signaling, error)) {
3212           return false;
3213         }
3214       } else if (HasAttribute(line, kAttributeCrypto)) {
3215         if (!ParseCryptoAttribute(line, media_desc, error)) {
3216           return false;
3217         }
3218       } else if (HasAttribute(line, kAttributeRtpmap)) {
3219         if (!ParseRtpmapAttribute(line, media_type, payload_types, media_desc,
3220                                   error)) {
3221           return false;
3222         }
3223       } else if (HasAttribute(line, kCodecParamMaxPTime)) {
3224         if (!GetValue(line, kCodecParamMaxPTime, &maxptime_as_string, error)) {
3225           return false;
3226         }
3227       } else if (HasAttribute(line, kAttributePacketization)) {
3228         if (!ParsePacketizationAttribute(line, media_type, media_desc, error)) {
3229           return false;
3230         }
3231       } else if (HasAttribute(line, kAttributeRtcpFb)) {
3232         if (!ParseRtcpFbAttribute(line, media_type, media_desc, error)) {
3233           return false;
3234         }
3235       } else if (HasAttribute(line, kCodecParamPTime)) {
3236         if (!GetValue(line, kCodecParamPTime, &ptime_as_string, error)) {
3237           return false;
3238         }
3239       } else if (HasAttribute(line, kAttributeSendOnly)) {
3240         media_desc->set_direction(RtpTransceiverDirection::kSendOnly);
3241       } else if (HasAttribute(line, kAttributeRecvOnly)) {
3242         media_desc->set_direction(RtpTransceiverDirection::kRecvOnly);
3243       } else if (HasAttribute(line, kAttributeInactive)) {
3244         media_desc->set_direction(RtpTransceiverDirection::kInactive);
3245       } else if (HasAttribute(line, kAttributeSendRecv)) {
3246         media_desc->set_direction(RtpTransceiverDirection::kSendRecv);
3247       } else if (HasAttribute(line, kAttributeExtmapAllowMixed)) {
3248         media_desc->set_extmap_allow_mixed_enum(
3249             MediaContentDescription::kMedia);
3250       } else if (HasAttribute(line, kAttributeExtmap)) {
3251         RtpExtension extmap;
3252         if (!ParseExtmap(line, &extmap, error)) {
3253           return false;
3254         }
3255         media_desc->AddRtpHeaderExtension(extmap);
3256       } else if (HasAttribute(line, kAttributeXGoogleFlag)) {
3257         // Experimental attribute.  Conference mode activates more aggressive
3258         // AEC and NS settings.
3259         // TODO(deadbeef): expose API to set these directly.
3260         std::string flag_value;
3261         if (!GetValue(line, kAttributeXGoogleFlag, &flag_value, error)) {
3262           return false;
3263         }
3264         if (flag_value.compare(kValueConference) == 0)
3265           media_desc->set_conference_mode(true);
3266       } else if (HasAttribute(line, kAttributeMsid)) {
3267         if (!ParseMsidAttribute(line, &stream_ids, &track_id, error)) {
3268           return false;
3269         }
3270         *msid_signaling |= cricket::kMsidSignalingMediaSection;
3271       } else if (HasAttribute(line, kAttributeRid)) {
3272         const size_t kRidPrefixLength =
3273             kLinePrefixLength + arraysize(kAttributeRid);
3274         if (line.size() <= kRidPrefixLength) {
3275           RTC_LOG(LS_INFO) << "Ignoring empty RID attribute: " << line;
3276           continue;
3277         }
3278         RTCErrorOr<RidDescription> error_or_rid_description =
3279             deserializer.DeserializeRidDescription(
3280                 line.substr(kRidPrefixLength));
3281 
3282         // Malformed a=rid lines are discarded.
3283         if (!error_or_rid_description.ok()) {
3284           RTC_LOG(LS_INFO) << "Ignoring malformed RID line: '" << line
3285                            << "'. Error: "
3286                            << error_or_rid_description.error().message();
3287           continue;
3288         }
3289 
3290         rids.push_back(error_or_rid_description.MoveValue());
3291       } else if (HasAttribute(line, kAttributeSimulcast)) {
3292         const size_t kSimulcastPrefixLength =
3293             kLinePrefixLength + arraysize(kAttributeSimulcast);
3294         if (line.size() <= kSimulcastPrefixLength) {
3295           return ParseFailed(line, "Simulcast attribute is empty.", error);
3296         }
3297 
3298         if (!simulcast.empty()) {
3299           return ParseFailed(line, "Multiple Simulcast attributes specified.",
3300                              error);
3301         }
3302 
3303         RTCErrorOr<SimulcastDescription> error_or_simulcast =
3304             deserializer.DeserializeSimulcastDescription(
3305                 line.substr(kSimulcastPrefixLength));
3306         if (!error_or_simulcast.ok()) {
3307           return ParseFailed(line,
3308                              std::string("Malformed simulcast line: ") +
3309                                  error_or_simulcast.error().message(),
3310                              error);
3311         }
3312 
3313         simulcast = error_or_simulcast.value();
3314       } else if (HasAttribute(line, kAttributeRtcp)) {
3315         // Ignore and do not log a=rtcp line.
3316         // JSEP  section 5.8.2 (media section parsing) says to ignore it.
3317         continue;
3318       } else {
3319         // Unrecognized attribute in RTP protocol.
3320         RTC_LOG(LS_VERBOSE) << "Ignored line: " << line;
3321         continue;
3322       }
3323     } else {
3324       // Only parse lines that we are interested of.
3325       RTC_LOG(LS_VERBOSE) << "Ignored line: " << line;
3326       continue;
3327     }
3328   }
3329 
3330   // Remove duplicate or inconsistent rids.
3331   RemoveInvalidRidDescriptions(payload_types, &rids);
3332 
3333   // If simulcast is specifed, split the rids into send and receive.
3334   // Rids that do not appear in simulcast attribute will be removed.
3335   // If it is not specified, we assume that all rids are for send layers.
3336   std::vector<RidDescription> send_rids;
3337   std::vector<RidDescription> receive_rids;
3338   if (!simulcast.empty()) {
3339     // Verify that the rids in simulcast match rids in sdp.
3340     RemoveInvalidRidsFromSimulcast(rids, &simulcast);
3341 
3342     // Use simulcast description to figure out Send / Receive RIDs.
3343     std::map<std::string, RidDescription> rid_map;
3344     for (const RidDescription& rid : rids) {
3345       rid_map[rid.rid] = rid;
3346     }
3347 
3348     for (const auto& layer : simulcast.send_layers().GetAllLayers()) {
3349       auto iter = rid_map.find(layer.rid);
3350       RTC_DCHECK(iter != rid_map.end());
3351       send_rids.push_back(iter->second);
3352     }
3353 
3354     for (const auto& layer : simulcast.receive_layers().GetAllLayers()) {
3355       auto iter = rid_map.find(layer.rid);
3356       RTC_DCHECK(iter != rid_map.end());
3357       receive_rids.push_back(iter->second);
3358     }
3359 
3360     media_desc->set_simulcast_description(simulcast);
3361   } else {
3362     send_rids = rids;
3363   }
3364 
3365   media_desc->set_receive_rids(receive_rids);
3366 
3367   // Create tracks from the |ssrc_infos|.
3368   // If the stream_id/track_id for all SSRCS are identical, one StreamParams
3369   // will be created in CreateTracksFromSsrcInfos, containing all the SSRCs from
3370   // the m= section.
3371   if (!ssrc_infos.empty()) {
3372     CreateTracksFromSsrcInfos(ssrc_infos, stream_ids, track_id, &tracks,
3373                               *msid_signaling);
3374   } else if (media_type != cricket::MEDIA_TYPE_DATA &&
3375              (*msid_signaling & cricket::kMsidSignalingMediaSection)) {
3376     // If the stream_ids/track_id was signaled but SSRCs were unsignaled we
3377     // still create a track. This isn't done for data media types because
3378     // StreamParams aren't used for SCTP streams, and RTP data channels don't
3379     // support unsignaled SSRCs.
3380     CreateTrackWithNoSsrcs(stream_ids, track_id, send_rids, &tracks);
3381   }
3382 
3383   // Add the ssrc group to the track.
3384   for (const SsrcGroup& ssrc_group : ssrc_groups) {
3385     if (ssrc_group.ssrcs.empty()) {
3386       continue;
3387     }
3388     uint32_t ssrc = ssrc_group.ssrcs.front();
3389     for (StreamParams& track : tracks) {
3390       if (track.has_ssrc(ssrc)) {
3391         track.ssrc_groups.push_back(ssrc_group);
3392       }
3393     }
3394   }
3395 
3396   // Add the new tracks to the |media_desc|.
3397   for (StreamParams& track : tracks) {
3398     media_desc->AddStream(track);
3399   }
3400 
3401   if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3402     AudioContentDescription* audio_desc = media_desc->as_audio();
3403     UpdateFromWildcardCodecs(audio_desc);
3404 
3405     // Verify audio codec ensures that no audio codec has been populated with
3406     // only fmtp.
3407     if (!VerifyAudioCodecs(audio_desc)) {
3408       return ParseFailed("Failed to parse audio codecs correctly.", error);
3409     }
3410     AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, audio_desc);
3411     AddAudioAttribute(kCodecParamPTime, ptime_as_string, audio_desc);
3412   }
3413 
3414   if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3415     VideoContentDescription* video_desc = media_desc->as_video();
3416     UpdateFromWildcardCodecs(video_desc);
3417     // Verify video codec ensures that no video codec has been populated with
3418     // only rtcp-fb.
3419     if (!VerifyVideoCodecs(video_desc)) {
3420       return ParseFailed("Failed to parse video codecs correctly.", error);
3421     }
3422   }
3423 
3424   // RFC 5245
3425   // Update the candidates with the media level "ice-pwd" and "ice-ufrag".
3426   for (Candidate& candidate : candidates_orig) {
3427     RTC_DCHECK(candidate.username().empty() ||
3428                candidate.username() == transport->ice_ufrag);
3429     candidate.set_username(transport->ice_ufrag);
3430     RTC_DCHECK(candidate.password().empty());
3431     candidate.set_password(transport->ice_pwd);
3432     candidates->push_back(
3433         std::make_unique<JsepIceCandidate>(mline_id, mline_index, candidate));
3434   }
3435 
3436   return true;
3437 }
3438 
ParseSsrcAttribute(const std::string & line,SsrcInfoVec * ssrc_infos,int * msid_signaling,SdpParseError * error)3439 bool ParseSsrcAttribute(const std::string& line,
3440                         SsrcInfoVec* ssrc_infos,
3441                         int* msid_signaling,
3442                         SdpParseError* error) {
3443   RTC_DCHECK(ssrc_infos != NULL);
3444   // RFC 5576
3445   // a=ssrc:<ssrc-id> <attribute>
3446   // a=ssrc:<ssrc-id> <attribute>:<value>
3447   std::string field1, field2;
3448   if (!rtc::tokenize_first(line.substr(kLinePrefixLength),
3449                            kSdpDelimiterSpaceChar, &field1, &field2)) {
3450     const size_t expected_fields = 2;
3451     return ParseFailedExpectFieldNum(line, expected_fields, error);
3452   }
3453 
3454   // ssrc:<ssrc-id>
3455   std::string ssrc_id_s;
3456   if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) {
3457     return false;
3458   }
3459   uint32_t ssrc_id = 0;
3460   if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) {
3461     return false;
3462   }
3463 
3464   std::string attribute;
3465   std::string value;
3466   if (!rtc::tokenize_first(field2, kSdpDelimiterColonChar, &attribute,
3467                            &value)) {
3468     rtc::StringBuilder description;
3469     description << "Failed to get the ssrc attribute value from " << field2
3470                 << ". Expected format <attribute>:<value>.";
3471     return ParseFailed(line, description.str(), error);
3472   }
3473 
3474   // Check if there's already an item for this |ssrc_id|. Create a new one if
3475   // there isn't.
3476   auto ssrc_info_it =
3477       absl::c_find_if(*ssrc_infos, [ssrc_id](const SsrcInfo& ssrc_info) {
3478         return ssrc_info.ssrc_id == ssrc_id;
3479       });
3480   if (ssrc_info_it == ssrc_infos->end()) {
3481     SsrcInfo info;
3482     info.ssrc_id = ssrc_id;
3483     ssrc_infos->push_back(info);
3484     ssrc_info_it = ssrc_infos->end() - 1;
3485   }
3486   SsrcInfo& ssrc_info = *ssrc_info_it;
3487 
3488   // Store the info to the |ssrc_info|.
3489   if (attribute == kSsrcAttributeCname) {
3490     // RFC 5576
3491     // cname:<value>
3492     ssrc_info.cname = value;
3493   } else if (attribute == kSsrcAttributeMsid) {
3494     // draft-alvestrand-mmusic-msid-00
3495     // msid:identifier [appdata]
3496     std::vector<std::string> fields;
3497     rtc::split(value, kSdpDelimiterSpaceChar, &fields);
3498     if (fields.size() < 1 || fields.size() > 2) {
3499       return ParseFailed(
3500           line, "Expected format \"msid:<identifier>[ <appdata>]\".", error);
3501     }
3502     ssrc_info.stream_id = fields[0];
3503     if (fields.size() == 2) {
3504       ssrc_info.track_id = fields[1];
3505     }
3506     *msid_signaling |= cricket::kMsidSignalingSsrcAttribute;
3507   } else if (attribute == kSsrcAttributeMslabel) {
3508     // draft-alvestrand-rtcweb-mid-01
3509     // mslabel:<value>
3510     ssrc_info.mslabel = value;
3511   } else if (attribute == kSSrcAttributeLabel) {
3512     // The label isn't defined.
3513     // label:<value>
3514     ssrc_info.label = value;
3515   }
3516   return true;
3517 }
3518 
ParseSsrcGroupAttribute(const std::string & line,SsrcGroupVec * ssrc_groups,SdpParseError * error)3519 bool ParseSsrcGroupAttribute(const std::string& line,
3520                              SsrcGroupVec* ssrc_groups,
3521                              SdpParseError* error) {
3522   RTC_DCHECK(ssrc_groups != NULL);
3523   // RFC 5576
3524   // a=ssrc-group:<semantics> <ssrc-id> ...
3525   std::vector<std::string> fields;
3526   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
3527   const size_t expected_min_fields = 2;
3528   if (fields.size() < expected_min_fields) {
3529     return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
3530   }
3531   std::string semantics;
3532   if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) {
3533     return false;
3534   }
3535   std::vector<uint32_t> ssrcs;
3536   for (size_t i = 1; i < fields.size(); ++i) {
3537     uint32_t ssrc = 0;
3538     if (!GetValueFromString(line, fields[i], &ssrc, error)) {
3539       return false;
3540     }
3541     ssrcs.push_back(ssrc);
3542   }
3543   ssrc_groups->push_back(SsrcGroup(semantics, ssrcs));
3544   return true;
3545 }
3546 
ParseCryptoAttribute(const std::string & line,MediaContentDescription * media_desc,SdpParseError * error)3547 bool ParseCryptoAttribute(const std::string& line,
3548                           MediaContentDescription* media_desc,
3549                           SdpParseError* error) {
3550   std::vector<std::string> fields;
3551   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
3552   // RFC 4568
3553   // a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
3554   const size_t expected_min_fields = 3;
3555   if (fields.size() < expected_min_fields) {
3556     return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
3557   }
3558   std::string tag_value;
3559   if (!GetValue(fields[0], kAttributeCrypto, &tag_value, error)) {
3560     return false;
3561   }
3562   int tag = 0;
3563   if (!GetValueFromString(line, tag_value, &tag, error)) {
3564     return false;
3565   }
3566   const std::string& crypto_suite = fields[1];
3567   const std::string& key_params = fields[2];
3568   std::string session_params;
3569   if (fields.size() > 3) {
3570     session_params = fields[3];
3571   }
3572   media_desc->AddCrypto(
3573       CryptoParams(tag, crypto_suite, key_params, session_params));
3574   return true;
3575 }
3576 
3577 // Updates or creates a new codec entry in the audio description with according
3578 // to |name|, |clockrate|, |bitrate|, and |channels|.
UpdateCodec(int payload_type,const std::string & name,int clockrate,int bitrate,size_t channels,AudioContentDescription * audio_desc)3579 void UpdateCodec(int payload_type,
3580                  const std::string& name,
3581                  int clockrate,
3582                  int bitrate,
3583                  size_t channels,
3584                  AudioContentDescription* audio_desc) {
3585   // Codec may already be populated with (only) optional parameters
3586   // (from an fmtp).
3587   cricket::AudioCodec codec =
3588       GetCodecWithPayloadType(audio_desc->codecs(), payload_type);
3589   codec.name = name;
3590   codec.clockrate = clockrate;
3591   codec.bitrate = bitrate;
3592   codec.channels = channels;
3593   AddOrReplaceCodec<AudioContentDescription, cricket::AudioCodec>(audio_desc,
3594                                                                   codec);
3595 }
3596 
3597 // Updates or creates a new codec entry in the video description according to
3598 // |name|, |width|, |height|, and |framerate|.
UpdateCodec(int payload_type,const std::string & name,VideoContentDescription * video_desc)3599 void UpdateCodec(int payload_type,
3600                  const std::string& name,
3601                  VideoContentDescription* video_desc) {
3602   // Codec may already be populated with (only) optional parameters
3603   // (from an fmtp).
3604   cricket::VideoCodec codec =
3605       GetCodecWithPayloadType(video_desc->codecs(), payload_type);
3606   codec.name = name;
3607   AddOrReplaceCodec<VideoContentDescription, cricket::VideoCodec>(video_desc,
3608                                                                   codec);
3609 }
3610 
ParseRtpmapAttribute(const std::string & line,const cricket::MediaType media_type,const std::vector<int> & payload_types,MediaContentDescription * media_desc,SdpParseError * error)3611 bool ParseRtpmapAttribute(const std::string& line,
3612                           const cricket::MediaType media_type,
3613                           const std::vector<int>& payload_types,
3614                           MediaContentDescription* media_desc,
3615                           SdpParseError* error) {
3616   std::vector<std::string> fields;
3617   rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, &fields);
3618   // RFC 4566
3619   // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
3620   const size_t expected_min_fields = 2;
3621   if (fields.size() < expected_min_fields) {
3622     return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
3623   }
3624   std::string payload_type_value;
3625   if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) {
3626     return false;
3627   }
3628   int payload_type = 0;
3629   if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type,
3630                                 error)) {
3631     return false;
3632   }
3633 
3634   if (!absl::c_linear_search(payload_types, payload_type)) {
3635     RTC_LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the "
3636                            "<fmt> of the m-line: "
3637                         << line;
3638     return true;
3639   }
3640   const std::string& encoder = fields[1];
3641   std::vector<std::string> codec_params;
3642   rtc::split(encoder, '/', &codec_params);
3643   // <encoding name>/<clock rate>[/<encodingparameters>]
3644   // 2 mandatory fields
3645   if (codec_params.size() < 2 || codec_params.size() > 3) {
3646     return ParseFailed(line,
3647                        "Expected format \"<encoding name>/<clock rate>"
3648                        "[/<encodingparameters>]\".",
3649                        error);
3650   }
3651   const std::string& encoding_name = codec_params[0];
3652   int clock_rate = 0;
3653   if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) {
3654     return false;
3655   }
3656   if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3657     VideoContentDescription* video_desc = media_desc->as_video();
3658     UpdateCodec(payload_type, encoding_name, video_desc);
3659   } else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3660     // RFC 4566
3661     // For audio streams, <encoding parameters> indicates the number
3662     // of audio channels.  This parameter is OPTIONAL and may be
3663     // omitted if the number of channels is one, provided that no
3664     // additional parameters are needed.
3665     size_t channels = 1;
3666     if (codec_params.size() == 3) {
3667       if (!GetValueFromString(line, codec_params[2], &channels, error)) {
3668         return false;
3669       }
3670     }
3671     AudioContentDescription* audio_desc = media_desc->as_audio();
3672     UpdateCodec(payload_type, encoding_name, clock_rate, 0, channels,
3673                 audio_desc);
3674   } else if (media_type == cricket::MEDIA_TYPE_DATA) {
3675     RtpDataContentDescription* data_desc = media_desc->as_rtp_data();
3676     if (data_desc) {
3677       data_desc->AddCodec(cricket::RtpDataCodec(payload_type, encoding_name));
3678     }
3679   }
3680   return true;
3681 }
3682 
ParseFmtpParam(const std::string & line,std::string * parameter,std::string * value,SdpParseError * error)3683 bool ParseFmtpParam(const std::string& line,
3684                     std::string* parameter,
3685                     std::string* value,
3686                     SdpParseError* error) {
3687   if (!rtc::tokenize_first(line, kSdpDelimiterEqualChar, parameter, value)) {
3688     // Support for non-key-value lines like RFC 2198 or RFC 4733.
3689     *parameter = "";
3690     *value = line;
3691     return true;
3692   }
3693   // a=fmtp:<payload_type> <param1>=<value1>; <param2>=<value2>; ...
3694   return true;
3695 }
3696 
ParseFmtpAttributes(const std::string & line,const cricket::MediaType media_type,MediaContentDescription * media_desc,SdpParseError * error)3697 bool ParseFmtpAttributes(const std::string& line,
3698                          const cricket::MediaType media_type,
3699                          MediaContentDescription* media_desc,
3700                          SdpParseError* error) {
3701   if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3702       media_type != cricket::MEDIA_TYPE_VIDEO) {
3703     return true;
3704   }
3705 
3706   std::string line_payload;
3707   std::string line_params;
3708 
3709   // https://tools.ietf.org/html/rfc4566#section-6
3710   // a=fmtp:<format> <format specific parameters>
3711   // At least two fields, whereas the second one is any of the optional
3712   // parameters.
3713   if (!rtc::tokenize_first(line.substr(kLinePrefixLength),
3714                            kSdpDelimiterSpaceChar, &line_payload,
3715                            &line_params)) {
3716     ParseFailedExpectMinFieldNum(line, 2, error);
3717     return false;
3718   }
3719 
3720   // Parse out the payload information.
3721   std::string payload_type_str;
3722   if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) {
3723     return false;
3724   }
3725 
3726   int payload_type = 0;
3727   if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type,
3728                                 error)) {
3729     return false;
3730   }
3731 
3732   // Parse out format specific parameters.
3733   std::vector<std::string> fields;
3734   rtc::split(line_params, kSdpDelimiterSemicolonChar, &fields);
3735 
3736   cricket::CodecParameterMap codec_params;
3737   for (auto& iter : fields) {
3738     std::string name;
3739     std::string value;
3740     if (!ParseFmtpParam(rtc::string_trim(iter), &name, &value, error)) {
3741       return false;
3742     }
3743     if (codec_params.find(name) != codec_params.end()) {
3744       RTC_LOG(LS_INFO) << "Overwriting duplicate fmtp parameter with key \""
3745                        << name << "\".";
3746     }
3747     codec_params[name] = value;
3748   }
3749 
3750   if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3751     UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3752         media_desc, payload_type, codec_params);
3753   } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3754     UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3755         media_desc, payload_type, codec_params);
3756   }
3757   return true;
3758 }
3759 
ParsePacketizationAttribute(const std::string & line,const cricket::MediaType media_type,MediaContentDescription * media_desc,SdpParseError * error)3760 bool ParsePacketizationAttribute(const std::string& line,
3761                                  const cricket::MediaType media_type,
3762                                  MediaContentDescription* media_desc,
3763                                  SdpParseError* error) {
3764   if (media_type != cricket::MEDIA_TYPE_VIDEO) {
3765     return true;
3766   }
3767   std::vector<std::string> packetization_fields;
3768   rtc::split(line.c_str(), kSdpDelimiterSpaceChar, &packetization_fields);
3769   if (packetization_fields.size() < 2) {
3770     return ParseFailedGetValue(line, kAttributePacketization, error);
3771   }
3772   std::string payload_type_string;
3773   if (!GetValue(packetization_fields[0], kAttributePacketization,
3774                 &payload_type_string, error)) {
3775     return false;
3776   }
3777   int payload_type;
3778   if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3779                                 error)) {
3780     return false;
3781   }
3782   std::string packetization = packetization_fields[1];
3783   UpdateVideoCodecPacketization(media_desc->as_video(), payload_type,
3784                                 packetization);
3785   return true;
3786 }
3787 
ParseRtcpFbAttribute(const std::string & line,const cricket::MediaType media_type,MediaContentDescription * media_desc,SdpParseError * error)3788 bool ParseRtcpFbAttribute(const std::string& line,
3789                           const cricket::MediaType media_type,
3790                           MediaContentDescription* media_desc,
3791                           SdpParseError* error) {
3792   if (media_type != cricket::MEDIA_TYPE_AUDIO &&
3793       media_type != cricket::MEDIA_TYPE_VIDEO) {
3794     return true;
3795   }
3796   std::vector<std::string> rtcp_fb_fields;
3797   rtc::split(line.c_str(), kSdpDelimiterSpaceChar, &rtcp_fb_fields);
3798   if (rtcp_fb_fields.size() < 2) {
3799     return ParseFailedGetValue(line, kAttributeRtcpFb, error);
3800   }
3801   std::string payload_type_string;
3802   if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string,
3803                 error)) {
3804     return false;
3805   }
3806   int payload_type = kWildcardPayloadType;
3807   if (payload_type_string != "*") {
3808     if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type,
3809                                   error)) {
3810       return false;
3811     }
3812   }
3813   std::string id = rtcp_fb_fields[1];
3814   std::string param = "";
3815   for (std::vector<std::string>::iterator iter = rtcp_fb_fields.begin() + 2;
3816        iter != rtcp_fb_fields.end(); ++iter) {
3817     param.append(*iter);
3818   }
3819   const cricket::FeedbackParam feedback_param(id, param);
3820 
3821   if (media_type == cricket::MEDIA_TYPE_AUDIO) {
3822     UpdateCodec<AudioContentDescription, cricket::AudioCodec>(
3823         media_desc, payload_type, feedback_param);
3824   } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
3825     UpdateCodec<VideoContentDescription, cricket::VideoCodec>(
3826         media_desc, payload_type, feedback_param);
3827   }
3828   return true;
3829 }
3830 
3831 }  // namespace webrtc
3832