2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2013, Digium, Inc.
6 * Joshua Colp <jcolp@digium.com>
7 * Kevin Harwell <kharwell@digium.com>
9 * See http://www.asterisk.org for more information about
10 * the Asterisk project. Please do not directly contact
11 * any of the maintainers of this project for assistance;
12 * the project provides a web site, mailing lists and IRC
13 * channels for your use.
15 * This program is free software, distributed under the terms of
16 * the GNU General Public License Version 2. See the LICENSE file
17 * at the top of the source tree.
22 * \author Joshua Colp <jcolp@digium.com>
24 * \brief SIP SDP media stream handling
28 <depend>pjproject</depend>
29 <depend>res_pjsip</depend>
30 <depend>res_pjsip_session</depend>
31 <support_level>core</support_level>
41 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43 #include "asterisk/module.h"
44 #include "asterisk/rtp_engine.h"
45 #include "asterisk/netsock2.h"
46 #include "asterisk/channel.h"
47 #include "asterisk/causes.h"
48 #include "asterisk/sched.h"
49 #include "asterisk/acl.h"
50 #include "asterisk/sdp_srtp.h"
52 #include "asterisk/res_pjsip.h"
53 #include "asterisk/res_pjsip_session.h"
55 /*! \brief Scheduler for RTCP purposes */
56 static struct ast_sched_context *sched;
58 /*! \brief Address for IPv4 RTP */
59 static struct ast_sockaddr address_ipv4;
61 /*! \brief Address for IPv6 RTP */
62 static struct ast_sockaddr address_ipv6;
64 static const char STR_AUDIO[] = "audio";
65 static const int FD_AUDIO = 0;
67 static const char STR_VIDEO[] = "video";
68 static const int FD_VIDEO = 2;
70 /*! \brief Retrieves an ast_format_type based on the given stream_type */
71 static enum ast_format_type stream_to_media_type(const char *stream_type)
73 if (!strcasecmp(stream_type, STR_AUDIO)) {
74 return AST_FORMAT_TYPE_AUDIO;
75 } else if (!strcasecmp(stream_type, STR_VIDEO)) {
76 return AST_FORMAT_TYPE_VIDEO;
82 /*! \brief Get the starting descriptor for a media type */
83 static int media_type_to_fdno(enum ast_format_type media_type)
86 case AST_FORMAT_TYPE_AUDIO: return FD_AUDIO;
87 case AST_FORMAT_TYPE_VIDEO: return FD_VIDEO;
88 case AST_FORMAT_TYPE_TEXT:
89 case AST_FORMAT_TYPE_IMAGE: break;
94 /*! \brief Remove all other cap types but the one given */
95 static void format_cap_only_type(struct ast_format_cap *caps, enum ast_format_type media_type)
97 int i = AST_FORMAT_INC;
98 while (i <= AST_FORMAT_TYPE_TEXT) {
99 if (i != media_type) {
100 ast_format_cap_remove_bytype(caps, i);
106 /*! \brief Internal function which creates an RTP instance */
107 static int create_rtp(struct ast_sip_session *session, struct ast_sip_session_media *session_media, unsigned int ipv6)
109 struct ast_rtp_engine_ice *ice;
111 if (!(session_media->rtp = ast_rtp_instance_new(session->endpoint->media.rtp.engine, sched, ipv6 ? &address_ipv6 : &address_ipv4, NULL))) {
112 ast_log(LOG_ERROR, "Unable to create RTP instance using RTP engine '%s'\n", session->endpoint->media.rtp.engine);
116 ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_RTCP, 1);
117 ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_NAT, session->endpoint->media.rtp.symmetric);
119 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(session_media->rtp),
120 session_media->rtp, &session->endpoint->media.prefs);
122 if (session->endpoint->dtmf == AST_SIP_DTMF_INBAND) {
123 ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_INBAND);
126 if (!session->endpoint->media.rtp.ice_support && (ice = ast_rtp_instance_get_ice(session_media->rtp))) {
127 ice->stop(session_media->rtp);
130 if (session->endpoint->dtmf == AST_SIP_DTMF_RFC_4733) {
131 ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_RFC2833);
132 } else if (session->endpoint->dtmf == AST_SIP_DTMF_INBAND) {
133 ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_INBAND);
136 if (!strcmp(session_media->stream_type, STR_AUDIO) &&
137 (session->endpoint->media.tos_audio || session->endpoint->media.cos_video)) {
138 ast_rtp_instance_set_qos(session_media->rtp, session->endpoint->media.tos_audio,
139 session->endpoint->media.cos_audio, "SIP RTP Audio");
140 } else if (!strcmp(session_media->stream_type, STR_VIDEO) &&
141 (session->endpoint->media.tos_video || session->endpoint->media.cos_video)) {
142 ast_rtp_instance_set_qos(session_media->rtp, session->endpoint->media.tos_video,
143 session->endpoint->media.cos_video, "SIP RTP Video");
149 static void get_codecs(struct ast_sip_session *session, const struct pjmedia_sdp_media *stream, struct ast_rtp_codecs *codecs)
151 pjmedia_sdp_attr *attr;
152 pjmedia_sdp_rtpmap *rtpmap;
153 pjmedia_sdp_fmtp fmtp;
154 struct ast_format *format;
160 ast_rtp_codecs_payloads_initialize(codecs);
162 /* Iterate through provided formats */
163 for (i = 0; i < stream->desc.fmt_count; ++i) {
164 /* The payload is kept as a string for things like t38 but for video it is always numerical */
165 ast_rtp_codecs_payloads_set_m_type(codecs, NULL, pj_strtoul(&stream->desc.fmt[i]));
166 /* Look for the optional rtpmap attribute */
167 if (!(attr = pjmedia_sdp_media_find_attr2(stream, "rtpmap", &stream->desc.fmt[i]))) {
171 /* Interpret the attribute as an rtpmap */
172 if ((pjmedia_sdp_attr_to_rtpmap(session->inv_session->pool_prov, attr, &rtpmap)) != PJ_SUCCESS) {
176 ast_copy_pj_str(name, &rtpmap->enc_name, sizeof(name));
177 ast_copy_pj_str(media, (pj_str_t*)&stream->desc.media, sizeof(media));
178 ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, NULL, pj_strtoul(&stream->desc.fmt[i]),
179 media, name, 0, rtpmap->clock_rate);
180 /* Look for an optional associated fmtp attribute */
181 if (!(attr = pjmedia_sdp_media_find_attr2(stream, "fmtp", &rtpmap->pt))) {
185 if ((pjmedia_sdp_attr_get_fmtp(attr, &fmtp)) == PJ_SUCCESS) {
186 sscanf(pj_strbuf(&fmtp.fmt), "%d", &num);
187 if ((format = ast_rtp_codecs_get_payload_format(codecs, num))) {
188 ast_copy_pj_str(fmt_param, &fmtp.fmt_param, sizeof(fmt_param));
189 ast_format_sdp_parse(format, fmt_param);
195 static int set_caps(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
196 const struct pjmedia_sdp_media *stream)
198 RAII_VAR(struct ast_format_cap *, caps, NULL, ast_format_cap_destroy);
199 RAII_VAR(struct ast_format_cap *, peer, NULL, ast_format_cap_destroy);
200 RAII_VAR(struct ast_format_cap *, joint, NULL, ast_format_cap_destroy);
201 enum ast_format_type media_type = stream_to_media_type(session_media->stream_type);
202 struct ast_rtp_codecs codecs;
203 struct ast_format fmt;
205 int direct_media_enabled = !ast_sockaddr_isnull(&session_media->direct_media_addr) &&
206 !ast_format_cap_is_empty(session->direct_media_cap);
208 if (!(caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK)) ||
209 !(peer = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK))) {
210 ast_log(LOG_ERROR, "Failed to allocate %s capabilities\n", session_media->stream_type);
214 /* get the endpoint capabilities */
215 if (direct_media_enabled) {
216 ast_format_cap_joint_copy(session->endpoint->media.codecs, session->direct_media_cap, caps);
218 ast_format_cap_copy(caps, session->endpoint->media.codecs);
220 format_cap_only_type(caps, media_type);
222 /* get the capabilities on the peer */
223 get_codecs(session, stream, &codecs);
224 ast_rtp_codecs_payload_formats(&codecs, peer, &fmts);
226 /* get the joint capabilities between peer and endpoint */
227 if (!(joint = ast_format_cap_joint(caps, peer))) {
228 char usbuf[64], thembuf[64];
230 ast_rtp_codecs_payloads_destroy(&codecs);
232 ast_getformatname_multiple(usbuf, sizeof(usbuf), caps);
233 ast_getformatname_multiple(thembuf, sizeof(thembuf), peer);
234 ast_log(LOG_WARNING, "No joint capabilities between our configuration(%s) and incoming SDP(%s)\n", usbuf, thembuf);
238 ast_rtp_codecs_payloads_copy(&codecs, ast_rtp_instance_get_codecs(session_media->rtp),
241 ast_format_cap_copy(caps, session->req_caps);
242 ast_format_cap_remove_bytype(caps, media_type);
243 ast_format_cap_append(caps, joint);
244 ast_format_cap_append(session->req_caps, caps);
246 if (session->channel) {
247 ast_format_cap_copy(caps, ast_channel_nativeformats(session->channel));
248 ast_format_cap_remove_bytype(caps, media_type);
249 ast_codec_choose(&session->endpoint->media.prefs, joint, 1, &fmt);
250 ast_format_cap_add(caps, &fmt);
252 /* Apply the new formats to the channel, potentially changing read/write formats while doing so */
253 ast_format_cap_copy(ast_channel_nativeformats(session->channel), caps);
254 ast_set_read_format(session->channel, ast_channel_readformat(session->channel));
255 ast_set_write_format(session->channel, ast_channel_writeformat(session->channel));
258 ast_rtp_codecs_payloads_destroy(&codecs);
262 static pjmedia_sdp_attr* generate_rtpmap_attr(pjmedia_sdp_media *media, pj_pool_t *pool, int rtp_code,
263 int asterisk_format, struct ast_format *format, int code)
265 pjmedia_sdp_rtpmap rtpmap;
266 pjmedia_sdp_attr *attr = NULL;
269 snprintf(tmp, sizeof(tmp), "%d", rtp_code);
270 pj_strdup2(pool, &media->desc.fmt[media->desc.fmt_count++], tmp);
271 rtpmap.pt = media->desc.fmt[media->desc.fmt_count - 1];
272 rtpmap.clock_rate = ast_rtp_lookup_sample_rate2(asterisk_format, format, code);
273 pj_strdup2(pool, &rtpmap.enc_name, ast_rtp_lookup_mime_subtype2(asterisk_format, format, code, 0));
274 rtpmap.param.slen = 0;
275 rtpmap.param.ptr = NULL;
277 pjmedia_sdp_rtpmap_to_attr(pool, &rtpmap, &attr);
282 static pjmedia_sdp_attr* generate_fmtp_attr(pj_pool_t *pool, struct ast_format *format, int rtp_code)
284 struct ast_str *fmtp0 = ast_str_alloca(256);
286 pjmedia_sdp_attr *attr = NULL;
289 ast_format_sdp_generate(format, rtp_code, &fmtp0);
290 if (ast_str_strlen(fmtp0)) {
291 tmp = ast_str_buffer(fmtp0) + ast_str_strlen(fmtp0) - 1;
292 /* remove any carriage return line feeds */
293 while (*tmp == '\r' || *tmp == '\n') --tmp;
295 /* ast...generate gives us everything, just need value */
296 tmp = strchr(ast_str_buffer(fmtp0), ':');
297 if (tmp && tmp + 1) {
298 fmtp1 = pj_str(tmp + 1);
300 fmtp1 = pj_str(ast_str_buffer(fmtp0));
302 attr = pjmedia_sdp_attr_create(pool, "fmtp", &fmtp1);
307 static int codec_pref_has_type(struct ast_codec_pref *prefs, enum ast_format_type media_type)
310 struct ast_format fmt;
311 for (i = 0; ast_codec_pref_index(prefs, i, &fmt); ++i) {
312 if (AST_FORMAT_GET_TYPE(fmt.id) == media_type) {
319 /*! \brief Function which adds ICE attributes to a media stream */
320 static void add_ice_to_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media, pj_pool_t *pool, pjmedia_sdp_media *media)
322 struct ast_rtp_engine_ice *ice;
323 struct ao2_container *candidates;
324 const char *username, *password;
326 pjmedia_sdp_attr *attr;
327 struct ao2_iterator it_candidates;
328 struct ast_rtp_engine_ice_candidate *candidate;
330 if (!session->endpoint->media.rtp.ice_support || !(ice = ast_rtp_instance_get_ice(session_media->rtp)) ||
331 !(candidates = ice->get_local_candidates(session_media->rtp))) {
335 if ((username = ice->get_ufrag(session_media->rtp))) {
336 attr = pjmedia_sdp_attr_create(pool, "ice-ufrag", pj_cstr(&stmp, username));
337 media->attr[media->attr_count++] = attr;
340 if ((password = ice->get_password(session_media->rtp))) {
341 attr = pjmedia_sdp_attr_create(pool, "ice-pwd", pj_cstr(&stmp, password));
342 media->attr[media->attr_count++] = attr;
345 it_candidates = ao2_iterator_init(candidates, 0);
346 for (; (candidate = ao2_iterator_next(&it_candidates)); ao2_ref(candidate, -1)) {
347 struct ast_str *attr_candidate = ast_str_create(128);
349 ast_str_set(&attr_candidate, -1, "%s %u %s %d %s ", candidate->foundation, candidate->id, candidate->transport,
350 candidate->priority, ast_sockaddr_stringify_host(&candidate->address));
351 ast_str_append(&attr_candidate, -1, "%s typ ", ast_sockaddr_stringify_port(&candidate->address));
353 switch (candidate->type) {
354 case AST_RTP_ICE_CANDIDATE_TYPE_HOST:
355 ast_str_append(&attr_candidate, -1, "host");
357 case AST_RTP_ICE_CANDIDATE_TYPE_SRFLX:
358 ast_str_append(&attr_candidate, -1, "srflx");
360 case AST_RTP_ICE_CANDIDATE_TYPE_RELAYED:
361 ast_str_append(&attr_candidate, -1, "relay");
365 if (!ast_sockaddr_isnull(&candidate->relay_address)) {
366 ast_str_append(&attr_candidate, -1, " raddr %s rport ", ast_sockaddr_stringify_host(&candidate->relay_address));
367 ast_str_append(&attr_candidate, -1, " %s", ast_sockaddr_stringify_port(&candidate->relay_address));
370 attr = pjmedia_sdp_attr_create(pool, "candidate", pj_cstr(&stmp, ast_str_buffer(attr_candidate)));
371 media->attr[media->attr_count++] = attr;
373 ast_free(attr_candidate);
376 ao2_iterator_destroy(&it_candidates);
379 /*! \brief Function which processes ICE attributes in an audio stream */
380 static void process_ice_attributes(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
381 const struct pjmedia_sdp_session *remote, const struct pjmedia_sdp_media *remote_stream)
383 struct ast_rtp_engine_ice *ice;
384 const pjmedia_sdp_attr *attr;
385 char attr_value[256];
388 /* If ICE support is not enabled or available exit early */
389 if (!session->endpoint->media.rtp.ice_support || !(ice = ast_rtp_instance_get_ice(session_media->rtp))) {
393 if ((attr = pjmedia_sdp_media_find_attr2(remote_stream, "ice-ufrag", NULL))) {
394 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
395 ice->set_authentication(session_media->rtp, attr_value, NULL);
398 if ((attr = pjmedia_sdp_media_find_attr2(remote_stream, "ice-pwd", NULL))) {
399 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
400 ice->set_authentication(session_media->rtp, NULL, attr_value);
403 if (pjmedia_sdp_media_find_attr2(remote_stream, "ice-lite", NULL)) {
404 ice->ice_lite(session_media->rtp);
407 /* Find all of the candidates */
408 for (attr_i = 0; attr_i < remote_stream->attr_count; ++attr_i) {
409 char foundation[32], transport[32], address[PJ_INET6_ADDRSTRLEN + 1], cand_type[6], relay_address[PJ_INET6_ADDRSTRLEN + 1] = "";
410 unsigned int port, relay_port = 0;
411 struct ast_rtp_engine_ice_candidate candidate = { 0, };
413 attr = remote_stream->attr[attr_i];
415 /* If this is not a candidate line skip it */
416 if (pj_strcmp2(&attr->name, "candidate")) {
420 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
422 if (sscanf(attr_value, "%31s %30u %31s %30u %46s %30u typ %5s %*s %23s %*s %30u", foundation, &candidate.id, transport,
423 (unsigned *)&candidate.priority, address, &port, cand_type, relay_address, &relay_port) < 7) {
424 /* Candidate did not parse properly */
428 candidate.foundation = foundation;
429 candidate.transport = transport;
431 ast_sockaddr_parse(&candidate.address, address, PARSE_PORT_FORBID);
432 ast_sockaddr_set_port(&candidate.address, port);
434 if (!strcasecmp(cand_type, "host")) {
435 candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
436 } else if (!strcasecmp(cand_type, "srflx")) {
437 candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
438 } else if (!strcasecmp(cand_type, "relay")) {
439 candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
444 if (!ast_strlen_zero(relay_address)) {
445 ast_sockaddr_parse(&candidate.relay_address, relay_address, PARSE_PORT_FORBID);
449 ast_sockaddr_set_port(&candidate.relay_address, relay_port);
452 ice->add_remote_candidate(session_media->rtp, &candidate);
455 ice->start(session_media->rtp);
458 static void apply_packetization(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
459 const struct pjmedia_sdp_media *remote_stream)
461 pjmedia_sdp_attr *attr;
463 unsigned long framing;
465 struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(session_media->rtp)->pref;
467 /* Apply packetization if available and configured to do so */
468 if (!session->endpoint->media.rtp.use_ptime || !(attr = pjmedia_sdp_media_find_attr2(remote_stream, "ptime", NULL))) {
473 framing = pj_strtoul(pj_strltrim(&value));
475 for (codec = 0; codec < AST_RTP_MAX_PT; codec++) {
476 struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(
477 session_media->rtp), codec);
479 if (!format.asterisk_format) {
483 ast_codec_pref_setsize(pref, &format.format, framing);
486 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(session_media->rtp),
487 session_media->rtp, pref);
490 /*! \brief figure out media transport encryption type from the media transport string */
491 static enum ast_sip_session_media_encryption get_media_encryption_type(pj_str_t transport)
493 RAII_VAR(char *, transport_str, ast_strndup(transport.ptr, transport.slen), ast_free);
494 if (strstr(transport_str, "UDP/TLS")) {
495 return AST_SIP_MEDIA_ENCRYPT_DTLS;
496 } else if (strstr(transport_str, "SAVP")) {
497 return AST_SIP_MEDIA_ENCRYPT_SDES;
499 return AST_SIP_MEDIA_ENCRYPT_NONE;
504 * \brief Checks whether the encryption offered in SDP is compatible with the endpoint's configuration
507 * \param endpoint_encryption Media encryption configured for the endpoint
508 * \param stream pjmedia_sdp_media stream description
510 * \retval AST_SIP_MEDIA_TRANSPORT_INVALID on encryption mismatch
511 * \retval The encryption requested in the SDP
513 static enum ast_sip_session_media_encryption check_endpoint_media_transport(
514 struct ast_sip_endpoint *endpoint,
515 const struct pjmedia_sdp_media *stream)
517 enum ast_sip_session_media_encryption incoming_encryption;
519 if (endpoint->media.rtp.use_avpf) {
520 char transport_end = stream->desc.transport.ptr[stream->desc.transport.slen - 1];
521 if (transport_end != 'F') {
522 return AST_SIP_MEDIA_TRANSPORT_INVALID;
526 incoming_encryption = get_media_encryption_type(stream->desc.transport);
528 if (incoming_encryption == endpoint->media.rtp.encryption) {
529 return incoming_encryption;
532 return AST_SIP_MEDIA_TRANSPORT_INVALID;
535 static int setup_srtp(struct ast_sip_session_media *session_media)
537 if (!session_media->srtp) {
538 session_media->srtp = ast_sdp_srtp_alloc();
539 if (!session_media->srtp) {
544 if (!session_media->srtp->crypto) {
545 session_media->srtp->crypto = ast_sdp_crypto_alloc();
546 if (!session_media->srtp->crypto) {
554 static int setup_dtls_srtp(struct ast_sip_session *session,
555 struct ast_sip_session_media *session_media)
557 struct ast_rtp_engine_dtls *dtls;
559 if (!session->endpoint->media.rtp.dtls_cfg.enabled || !session_media->rtp) {
563 dtls = ast_rtp_instance_get_dtls(session_media->rtp);
568 session->endpoint->media.rtp.dtls_cfg.suite = ((session->endpoint->media.rtp.srtp_tag_32) ? AST_AES_CM_128_HMAC_SHA1_32 : AST_AES_CM_128_HMAC_SHA1_80);
569 if (dtls->set_configuration(session_media->rtp, &session->endpoint->media.rtp.dtls_cfg)) {
570 ast_log(LOG_ERROR, "Attempted to set an invalid DTLS-SRTP configuration on RTP instance '%p'\n",
575 if (setup_srtp(session_media)) {
581 static int parse_dtls_attrib(struct ast_sip_session_media *session_media,
582 const struct pjmedia_sdp_media *stream)
585 struct ast_rtp_engine_dtls *dtls = ast_rtp_instance_get_dtls(session_media->rtp);
587 for (i = 0; i < stream->attr_count; i++) {
588 pjmedia_sdp_attr *attr = stream->attr[i];
591 if (!attr->value.ptr) {
595 value = pj_strtrim(&attr->value);
597 if (!pj_strcmp2(&attr->name, "setup")) {
598 if (!pj_stricmp2(value, "active")) {
599 dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_ACTIVE);
600 } else if (!pj_stricmp2(value, "passive")) {
601 dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_PASSIVE);
602 } else if (!pj_stricmp2(value, "actpass")) {
603 dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_ACTPASS);
604 } else if (!pj_stricmp2(value, "holdconn")) {
605 dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_HOLDCONN);
607 ast_log(LOG_WARNING, "Unsupported setup attribute value '%*s'\n", (int)value->slen, value->ptr);
609 } else if (!pj_strcmp2(&attr->name, "connection")) {
610 if (!pj_stricmp2(value, "new")) {
611 dtls->reset(session_media->rtp);
612 } else if (!pj_stricmp2(value, "existing")) {
615 ast_log(LOG_WARNING, "Unsupported connection attribute value '%*s'\n", (int)value->slen, value->ptr);
617 } else if (!pj_strcmp2(&attr->name, "fingerprint")) {
618 char hash_value[256], hash[6];
619 char fingerprint_text[value->slen + 1];
620 ast_copy_pj_str(fingerprint_text, value, sizeof(fingerprint_text));
622 if (sscanf(fingerprint_text, "%5s %255s", hash, hash_value) == 2) {
623 if (!strcasecmp(hash, "sha-1")) {
624 dtls->set_fingerprint(session_media->rtp, AST_RTP_DTLS_HASH_SHA1, hash_value);
626 ast_log(LOG_WARNING, "Unsupported fingerprint hash type '%s'\n",
632 ast_set_flag(session_media->srtp, AST_SRTP_CRYPTO_OFFER_OK);
637 static int setup_sdes_srtp(struct ast_sip_session_media *session_media,
638 const struct pjmedia_sdp_media *stream)
642 for (i = 0; i < stream->attr_count; i++) {
643 pjmedia_sdp_attr *attr;
644 RAII_VAR(char *, crypto_str, NULL, ast_free);
646 /* check the stream for the required crypto attribute */
647 attr = stream->attr[i];
648 if (pj_strcmp2(&attr->name, "crypto")) {
652 crypto_str = ast_strndup(attr->value.ptr, attr->value.slen);
657 if (setup_srtp(session_media)) {
661 if (!ast_sdp_crypto_process(session_media->rtp, session_media->srtp, crypto_str)) {
662 /* found a valid crypto attribute */
666 ast_debug(1, "Ignoring crypto offer with unsupported parameters: %s\n", crypto_str);
669 /* no usable crypto attributes found */
673 static int setup_media_encryption(struct ast_sip_session *session,
674 struct ast_sip_session_media *session_media,
675 const struct pjmedia_sdp_media *stream)
677 switch (session->endpoint->media.rtp.encryption) {
678 case AST_SIP_MEDIA_ENCRYPT_SDES:
679 if (setup_sdes_srtp(session_media, stream)) {
683 case AST_SIP_MEDIA_ENCRYPT_DTLS:
684 if (setup_dtls_srtp(session, session_media)) {
687 if (parse_dtls_attrib(session_media, stream)) {
691 case AST_SIP_MEDIA_TRANSPORT_INVALID:
692 case AST_SIP_MEDIA_ENCRYPT_NONE:
699 /*! \brief Function which negotiates an incoming media stream */
700 static int negotiate_incoming_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
701 const struct pjmedia_sdp_session *sdp, const struct pjmedia_sdp_media *stream)
703 char host[NI_MAXHOST];
704 RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free_ptr);
705 enum ast_format_type media_type = stream_to_media_type(session_media->stream_type);
707 /* If no type formats have been configured reject this stream */
708 if (!ast_format_cap_has_type(session->endpoint->media.codecs, media_type)) {
712 /* Ensure incoming transport is compatible with the endpoint's configuration */
713 if (check_endpoint_media_transport(session->endpoint, stream) == AST_SIP_MEDIA_TRANSPORT_INVALID) {
717 ast_copy_pj_str(host, stream->conn ? &stream->conn->addr : &sdp->conn->addr, sizeof(host));
719 /* Ensure that the address provided is valid */
720 if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
721 /* The provided host was actually invalid so we error out this negotiation */
725 /* Using the connection information create an appropriate RTP instance */
726 if (!session_media->rtp && create_rtp(session, session_media, ast_sockaddr_is_ipv6(addrs))) {
730 if (setup_media_encryption(session, session_media, stream)) {
734 if (set_caps(session, session_media, stream)) {
738 if (media_type == AST_FORMAT_TYPE_AUDIO) {
739 apply_packetization(session, session_media, stream);
745 static int add_crypto_to_stream(struct ast_sip_session *session,
746 struct ast_sip_session_media *session_media,
747 pj_pool_t *pool, pjmedia_sdp_media *media)
750 pjmedia_sdp_attr *attr;
751 const char *crypto_attribute;
752 struct ast_rtp_engine_dtls *dtls;
753 static const pj_str_t STR_NEW = { "new", 3 };
754 static const pj_str_t STR_EXISTING = { "existing", 8 };
755 static const pj_str_t STR_ACTIVE = { "active", 6 };
756 static const pj_str_t STR_PASSIVE = { "passive", 7 };
757 static const pj_str_t STR_ACTPASS = { "actpass", 7 };
758 static const pj_str_t STR_HOLDCONN = { "holdconn", 8 };
760 switch (session->endpoint->media.rtp.encryption) {
761 case AST_SIP_MEDIA_ENCRYPT_NONE:
762 case AST_SIP_MEDIA_TRANSPORT_INVALID:
764 case AST_SIP_MEDIA_ENCRYPT_SDES:
765 if (!session_media->srtp) {
766 session_media->srtp = ast_sdp_srtp_alloc();
767 if (!session_media->srtp) {
772 crypto_attribute = ast_sdp_srtp_get_attrib(session_media->srtp,
773 0 /* DTLS running? No */,
774 session->endpoint->media.rtp.srtp_tag_32 /* 32 byte tag length? */);
775 if (!crypto_attribute) {
776 /* No crypto attribute to add, bad news */
780 attr = pjmedia_sdp_attr_create(pool, "crypto", pj_cstr(&stmp, crypto_attribute));
781 media->attr[media->attr_count++] = attr;
783 case AST_SIP_MEDIA_ENCRYPT_DTLS:
784 if (setup_dtls_srtp(session, session_media)) {
788 dtls = ast_rtp_instance_get_dtls(session_media->rtp);
793 switch (dtls->get_connection(session_media->rtp)) {
794 case AST_RTP_DTLS_CONNECTION_NEW:
795 attr = pjmedia_sdp_attr_create(pool, "connection", &STR_NEW);
796 media->attr[media->attr_count++] = attr;
798 case AST_RTP_DTLS_CONNECTION_EXISTING:
799 attr = pjmedia_sdp_attr_create(pool, "connection", &STR_EXISTING);
800 media->attr[media->attr_count++] = attr;
806 switch (dtls->get_setup(session_media->rtp)) {
807 case AST_RTP_DTLS_SETUP_ACTIVE:
808 attr = pjmedia_sdp_attr_create(pool, "setup", &STR_ACTIVE);
809 media->attr[media->attr_count++] = attr;
811 case AST_RTP_DTLS_SETUP_PASSIVE:
812 attr = pjmedia_sdp_attr_create(pool, "setup", &STR_PASSIVE);
813 media->attr[media->attr_count++] = attr;
815 case AST_RTP_DTLS_SETUP_ACTPASS:
816 attr = pjmedia_sdp_attr_create(pool, "setup", &STR_ACTPASS);
817 media->attr[media->attr_count++] = attr;
819 case AST_RTP_DTLS_SETUP_HOLDCONN:
820 attr = pjmedia_sdp_attr_create(pool, "setup", &STR_HOLDCONN);
821 media->attr[media->attr_count++] = attr;
827 if ((crypto_attribute = dtls->get_fingerprint(session_media->rtp, AST_RTP_DTLS_HASH_SHA1))) {
828 RAII_VAR(struct ast_str *, fingerprint, ast_str_create(64), ast_free);
833 ast_str_set(&fingerprint, 0, "SHA-1 %s", crypto_attribute);
835 attr = pjmedia_sdp_attr_create(pool, "fingerprint", pj_cstr(&stmp, ast_str_buffer(fingerprint)));
836 media->attr[media->attr_count++] = attr;
844 /*! \brief Function which creates an outgoing stream */
845 static int create_outgoing_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
846 struct pjmedia_sdp_session *sdp)
848 pj_pool_t *pool = session->inv_session->pool_prov;
849 static const pj_str_t STR_IN = { "IN", 2 };
850 static const pj_str_t STR_IP4 = { "IP4", 3};
851 static const pj_str_t STR_IP6 = { "IP6", 3};
852 static const pj_str_t STR_SENDRECV = { "sendrecv", 8 };
853 pjmedia_sdp_media *media;
854 char hostip[PJ_INET6_ADDRSTRLEN+2];
855 struct ast_sockaddr addr;
858 pjmedia_sdp_attr *attr;
860 int noncodec = (session->endpoint->dtmf == AST_SIP_DTMF_RFC_4733) ? AST_RTP_DTMF : 0;
861 int min_packet_size = 0, max_packet_size = 0;
863 struct ast_format format;
864 RAII_VAR(struct ast_format_cap *, caps, NULL, ast_format_cap_destroy);
865 enum ast_format_type media_type = stream_to_media_type(session_media->stream_type);
867 int direct_media_enabled = !ast_sockaddr_isnull(&session_media->direct_media_addr) &&
868 !ast_format_cap_is_empty(session->direct_media_cap);
870 int use_override_prefs = session->override_prefs.formats[0].id;
871 struct ast_codec_pref *prefs = use_override_prefs ?
872 &session->override_prefs : &session->endpoint->media.prefs;
874 if ((use_override_prefs && !codec_pref_has_type(&session->override_prefs, media_type)) ||
875 (!use_override_prefs && !ast_format_cap_has_type(session->endpoint->media.codecs, media_type))) {
876 /* If no type formats are configured don't add a stream */
878 } else if (!session_media->rtp && create_rtp(session, session_media, session->endpoint->media.rtp.ipv6)) {
882 if (!(media = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_media))) ||
883 !(media->conn = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_conn)))) {
887 if (add_crypto_to_stream(session, session_media, pool, media)) {
891 media->desc.media = pj_str(session_media->stream_type);
892 media->desc.transport = pj_str(ast_sdp_get_rtp_profile(
893 session->endpoint->media.rtp.encryption == AST_SIP_MEDIA_ENCRYPT_SDES,
894 session_media->rtp, session->endpoint->media.rtp.use_avpf));
896 /* Add connection level details */
897 if (direct_media_enabled) {
898 ast_copy_string(hostip, ast_sockaddr_stringify_fmt(&session_media->direct_media_addr, AST_SOCKADDR_STR_ADDR), sizeof(hostip));
899 } else if (ast_strlen_zero(session->endpoint->media.address)) {
900 pj_sockaddr localaddr;
902 if (pj_gethostip(session->endpoint->media.rtp.ipv6 ? pj_AF_INET6() : pj_AF_INET(), &localaddr)) {
905 pj_sockaddr_print(&localaddr, hostip, sizeof(hostip), 2);
907 ast_copy_string(hostip, session->endpoint->media.address, sizeof(hostip));
910 media->conn->net_type = STR_IN;
911 media->conn->addr_type = session->endpoint->media.rtp.ipv6 ? STR_IP6 : STR_IP4;
912 pj_strdup2(pool, &media->conn->addr, hostip);
913 ast_rtp_instance_get_local_address(session_media->rtp, &addr);
914 media->desc.port = direct_media_enabled ? ast_sockaddr_port(&session_media->direct_media_addr) : (pj_uint16_t) ast_sockaddr_port(&addr);
915 media->desc.port_count = 1;
917 /* Add ICE attributes and candidates */
918 add_ice_to_stream(session, session_media, pool, media);
920 if (!(caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK))) {
921 ast_log(LOG_ERROR, "Failed to allocate %s capabilities\n", session_media->stream_type);
925 if (direct_media_enabled) {
926 ast_format_cap_joint_copy(session->endpoint->media.codecs, session->direct_media_cap, caps);
927 } else if (ast_format_cap_is_empty(session->req_caps) || !ast_format_cap_has_joint(session->req_caps, session->endpoint->media.codecs)) {
928 ast_format_cap_copy(caps, session->endpoint->media.codecs);
930 ast_format_cap_copy(caps, session->req_caps);
933 for (index = 0; ast_codec_pref_index(prefs, index, &format); ++index) {
934 struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(session_media->rtp)->pref;
936 if (AST_FORMAT_GET_TYPE(format.id) != media_type) {
940 if (!use_override_prefs && !ast_format_cap_get_compatible_format(caps, &format, &format)) {
944 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(session_media->rtp), 1, &format, 0)) == -1) {
945 ast_log(LOG_WARNING,"Unable to get rtp codec payload code for %s\n",ast_getformatname(&format));
949 if (!(attr = generate_rtpmap_attr(media, pool, rtp_code, 1, &format, 0))) {
953 media->attr[media->attr_count++] = attr;
955 if ((attr = generate_fmtp_attr(pool, &format, rtp_code))) {
956 media->attr[media->attr_count++] = attr;
959 if (pref && media_type != AST_FORMAT_TYPE_VIDEO) {
960 struct ast_format_list fmt = ast_codec_pref_getsize(pref, &format);
961 if (fmt.cur_ms && ((fmt.cur_ms < min_packet_size) || !min_packet_size)) {
962 min_packet_size = fmt.cur_ms;
965 if (fmt.max_ms && ((fmt.max_ms < max_packet_size) || !max_packet_size)) {
966 max_packet_size = fmt.max_ms;
971 /* Add non-codec formats */
972 if (media_type != AST_FORMAT_TYPE_VIDEO) {
973 for (index = 1LL; index <= AST_RTP_MAX; index <<= 1) {
974 if (!(noncodec & index) || (rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(session_media->rtp),
975 0, NULL, index)) == -1) {
979 if (!(attr = generate_rtpmap_attr(media, pool, rtp_code, 0, NULL, index))) {
983 media->attr[media->attr_count++] = attr;
985 if (index == AST_RTP_DTMF) {
986 snprintf(tmp, sizeof(tmp), "%d 0-16", rtp_code);
987 attr = pjmedia_sdp_attr_create(pool, "fmtp", pj_cstr(&stmp, tmp));
988 media->attr[media->attr_count++] = attr;
993 /* If no formats were actually added to the media stream don't add it to the SDP */
994 if (!media->desc.fmt_count) {
998 /* If ptime is set add it as an attribute */
999 if (min_packet_size) {
1000 snprintf(tmp, sizeof(tmp), "%d", min_packet_size);
1001 attr = pjmedia_sdp_attr_create(pool, "ptime", pj_cstr(&stmp, tmp));
1002 media->attr[media->attr_count++] = attr;
1005 if (max_packet_size) {
1006 snprintf(tmp, sizeof(tmp), "%d", max_packet_size);
1007 attr = pjmedia_sdp_attr_create(pool, "maxptime", pj_cstr(&stmp, tmp));
1008 media->attr[media->attr_count++] = attr;
1011 /* Add the sendrecv attribute - we purposely don't keep track because pjmedia-sdp will automatically change our offer for us */
1012 attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr);
1013 attr->name = STR_SENDRECV;
1014 media->attr[media->attr_count++] = attr;
1016 /* Add the media stream to the SDP */
1017 sdp->media[sdp->media_count++] = media;
1022 static int apply_negotiated_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
1023 const struct pjmedia_sdp_session *local, const struct pjmedia_sdp_media *local_stream,
1024 const struct pjmedia_sdp_session *remote, const struct pjmedia_sdp_media *remote_stream)
1026 RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free_ptr);
1027 enum ast_format_type media_type = stream_to_media_type(session_media->stream_type);
1028 char host[NI_MAXHOST];
1031 if (!session->channel) {
1035 /* Ensure incoming transport is compatible with the endpoint's configuration */
1036 if (check_endpoint_media_transport(session->endpoint, remote_stream) == AST_SIP_MEDIA_TRANSPORT_INVALID) {
1040 /* Create an RTP instance if need be */
1041 if (!session_media->rtp && create_rtp(session, session_media, session->endpoint->media.rtp.ipv6)) {
1045 if (setup_media_encryption(session, session_media, remote_stream)) {
1049 ast_copy_pj_str(host, remote_stream->conn ? &remote_stream->conn->addr : &remote->conn->addr, sizeof(host));
1051 /* Ensure that the address provided is valid */
1052 if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
1053 /* The provided host was actually invalid so we error out this negotiation */
1057 /* Apply connection information to the RTP instance */
1058 ast_sockaddr_set_port(addrs, remote_stream->desc.port);
1059 ast_rtp_instance_set_remote_address(session_media->rtp, addrs);
1061 if (set_caps(session, session_media, local_stream)) {
1065 if (media_type == AST_FORMAT_TYPE_AUDIO) {
1066 apply_packetization(session, session_media, remote_stream);
1069 if ((fdno = media_type_to_fdno(media_type)) < 0) {
1072 ast_channel_set_fd(session->channel, fdno, ast_rtp_instance_fd(session_media->rtp, 0));
1073 ast_channel_set_fd(session->channel, fdno + 1, ast_rtp_instance_fd(session_media->rtp, 1));
1075 /* If ICE support is enabled find all the needed attributes */
1076 process_ice_attributes(session, session_media, remote, remote_stream);
1078 /* Ensure the RTP instance is active */
1079 ast_rtp_instance_activate(session_media->rtp);
1081 /* audio stream handles music on hold */
1082 if (media_type != AST_FORMAT_TYPE_AUDIO) {
1086 if (ast_sockaddr_isnull(addrs) ||
1087 ast_sockaddr_is_any(addrs) ||
1088 pjmedia_sdp_media_find_attr2(remote_stream, "sendonly", NULL)) {
1089 if (!session_media->held) {
1090 /* The remote side has put us on hold */
1091 ast_queue_hold(session->channel, session->endpoint->mohsuggest);
1092 ast_rtp_instance_stop(session_media->rtp);
1093 ast_queue_frame(session->channel, &ast_null_frame);
1094 session_media->held = 1;
1096 } else if (session_media->held) {
1097 /* The remote side has taken us off hold */
1098 ast_queue_unhold(session->channel);
1099 ast_queue_frame(session->channel, &ast_null_frame);
1100 session_media->held = 0;
1106 /*! \brief Function which updates the media stream with external media address, if applicable */
1107 static void change_outgoing_sdp_stream_media_address(pjsip_tx_data *tdata, struct pjmedia_sdp_media *stream, struct ast_sip_transport *transport)
1109 char host[NI_MAXHOST];
1110 struct ast_sockaddr addr = { { 0, } };
1112 /* If the stream has been rejected there will be no connection line */
1113 if (!stream->conn) {
1117 ast_copy_pj_str(host, &stream->conn->addr, sizeof(host));
1118 ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID);
1120 /* Is the address within the SDP inside the same network? */
1121 if (ast_apply_ha(transport->localnet, &addr) == AST_SENSE_ALLOW) {
1125 pj_strdup2(tdata->pool, &stream->conn->addr, transport->external_media_address);
1128 /*! \brief Function which destroys the RTP instance when session ends */
1129 static void stream_destroy(struct ast_sip_session_media *session_media)
1131 if (session_media->rtp) {
1132 ast_rtp_instance_stop(session_media->rtp);
1133 ast_rtp_instance_destroy(session_media->rtp);
1137 /*! \brief SDP handler for 'audio' media stream */
1138 static struct ast_sip_session_sdp_handler audio_sdp_handler = {
1140 .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
1141 .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
1142 .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
1143 .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
1144 .stream_destroy = stream_destroy,
1147 /*! \brief SDP handler for 'video' media stream */
1148 static struct ast_sip_session_sdp_handler video_sdp_handler = {
1150 .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
1151 .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
1152 .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
1153 .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
1154 .stream_destroy = stream_destroy,
1157 static int video_info_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
1159 struct pjsip_transaction *tsx = pjsip_rdata_get_tsx(rdata);
1160 pjsip_tx_data *tdata;
1162 if (!ast_sip_is_content_type(&rdata->msg_info.msg->body->content_type,
1164 "media_control+xml")) {
1168 ast_queue_control(session->channel, AST_CONTROL_VIDUPDATE);
1170 if (pjsip_dlg_create_response(session->inv_session->dlg, rdata, 200, NULL, &tdata) == PJ_SUCCESS) {
1171 pjsip_dlg_send_response(session->inv_session->dlg, tsx, tdata);
1177 static struct ast_sip_session_supplement video_info_supplement = {
1179 .incoming_request = video_info_incoming_request,
1182 /*! \brief Unloads the sdp RTP/AVP module from Asterisk */
1183 static int unload_module(void)
1185 ast_sip_session_unregister_supplement(&video_info_supplement);
1186 ast_sip_session_unregister_sdp_handler(&video_sdp_handler, STR_VIDEO);
1187 ast_sip_session_unregister_sdp_handler(&audio_sdp_handler, STR_AUDIO);
1190 ast_sched_context_destroy(sched);
1197 * \brief Load the module
1199 * Module loading including tests for configuration or dependencies.
1200 * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1201 * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1202 * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
1203 * configuration file or other non-critical problem return
1204 * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1206 static int load_module(void)
1208 ast_sockaddr_parse(&address_ipv4, "0.0.0.0", 0);
1209 ast_sockaddr_parse(&address_ipv6, "::", 0);
1211 if (!(sched = ast_sched_context_create())) {
1212 ast_log(LOG_ERROR, "Unable to create scheduler context.\n");
1216 if (ast_sched_start_thread(sched)) {
1217 ast_log(LOG_ERROR, "Unable to create scheduler context thread.\n");
1221 if (ast_sip_session_register_sdp_handler(&audio_sdp_handler, STR_AUDIO)) {
1222 ast_log(LOG_ERROR, "Unable to register SDP handler for %s stream type\n", STR_AUDIO);
1226 if (ast_sip_session_register_sdp_handler(&video_sdp_handler, STR_VIDEO)) {
1227 ast_log(LOG_ERROR, "Unable to register SDP handler for %s stream type\n", STR_VIDEO);
1231 ast_sip_session_register_supplement(&video_info_supplement);
1233 return AST_MODULE_LOAD_SUCCESS;
1237 return AST_MODULE_LOAD_FAILURE;
1240 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP SDP RTP/AVP stream handler",
1241 .load = load_module,
1242 .unload = unload_module,
1243 .load_pri = AST_MODPRI_CHANNEL_DRIVER,