res_pjsip_sdp_rtp.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 2013, Digium, Inc.
00005  *
00006  * Joshua Colp <jcolp@digium.com>
00007  * Kevin Harwell <kharwell@digium.com>
00008  *
00009  * See http://www.asterisk.org for more information about
00010  * the Asterisk project. Please do not directly contact
00011  * any of the maintainers of this project for assistance;
00012  * the project provides a web site, mailing lists and IRC
00013  * channels for your use.
00014  *
00015  * This program is free software, distributed under the terms of
00016  * the GNU General Public License Version 2. See the LICENSE file
00017  * at the top of the source tree.
00018  */
00019 
00020 /*! \file
00021  *
00022  * \author Joshua Colp <jcolp@digium.com>
00023  *
00024  * \brief SIP SDP media stream handling
00025  */
00026 
00027 /*** MODULEINFO
00028    <depend>pjproject</depend>
00029    <depend>res_pjsip</depend>
00030    <depend>res_pjsip_session</depend>
00031    <support_level>core</support_level>
00032  ***/
00033 
00034 #include "asterisk.h"
00035 
00036 #include <pjsip.h>
00037 #include <pjsip_ua.h>
00038 #include <pjmedia.h>
00039 #include <pjlib.h>
00040 
00041 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 434672 $")
00042 
00043 #include "asterisk/module.h"
00044 #include "asterisk/format.h"
00045 #include "asterisk/format_cap.h"
00046 #include "asterisk/rtp_engine.h"
00047 #include "asterisk/netsock2.h"
00048 #include "asterisk/channel.h"
00049 #include "asterisk/causes.h"
00050 #include "asterisk/sched.h"
00051 #include "asterisk/acl.h"
00052 #include "asterisk/sdp_srtp.h"
00053 #include "asterisk/dsp.h"
00054 
00055 #include "asterisk/res_pjsip.h"
00056 #include "asterisk/res_pjsip_session.h"
00057 
00058 /*! \brief Scheduler for RTCP purposes */
00059 static struct ast_sched_context *sched;
00060 
00061 /*! \brief Address for IPv4 RTP */
00062 static struct ast_sockaddr address_ipv4;
00063 
00064 /*! \brief Address for IPv6 RTP */
00065 static struct ast_sockaddr address_ipv6;
00066 
00067 static const char STR_AUDIO[] = "audio";
00068 static const int FD_AUDIO = 0;
00069 
00070 static const char STR_VIDEO[] = "video";
00071 static const int FD_VIDEO = 2;
00072 
00073 /*! \brief Retrieves an ast_format_type based on the given stream_type */
00074 static enum ast_media_type stream_to_media_type(const char *stream_type)
00075 {
00076    if (!strcasecmp(stream_type, STR_AUDIO)) {
00077       return AST_MEDIA_TYPE_AUDIO;
00078    } else if (!strcasecmp(stream_type, STR_VIDEO)) {
00079       return AST_MEDIA_TYPE_VIDEO;
00080    }
00081 
00082    return 0;
00083 }
00084 
00085 /*! \brief Get the starting descriptor for a media type */
00086 static int media_type_to_fdno(enum ast_media_type media_type)
00087 {
00088    switch (media_type) {
00089    case AST_MEDIA_TYPE_AUDIO: return FD_AUDIO;
00090    case AST_MEDIA_TYPE_VIDEO: return FD_VIDEO;
00091    case AST_MEDIA_TYPE_TEXT:
00092    case AST_MEDIA_TYPE_UNKNOWN:
00093    case AST_MEDIA_TYPE_IMAGE: break;
00094    }
00095    return -1;
00096 }
00097 
00098 /*! \brief Remove all other cap types but the one given */
00099 static void format_cap_only_type(struct ast_format_cap *caps, enum ast_media_type media_type)
00100 {
00101    int i = 0;
00102    while (i <= AST_MEDIA_TYPE_TEXT) {
00103       if (i != media_type && i != AST_MEDIA_TYPE_UNKNOWN) {
00104          ast_format_cap_remove_by_type(caps, i);
00105       }
00106       i += 1;
00107    }
00108 }
00109 
00110 /*! \brief Internal function which creates an RTP instance */
00111 static int create_rtp(struct ast_sip_session *session, struct ast_sip_session_media *session_media, unsigned int ipv6)
00112 {
00113    struct ast_rtp_engine_ice *ice;
00114 
00115    if (!(session_media->rtp = ast_rtp_instance_new(session->endpoint->media.rtp.engine, sched, ipv6 ? &address_ipv6 : &address_ipv4, NULL))) {
00116       ast_log(LOG_ERROR, "Unable to create RTP instance using RTP engine '%s'\n", session->endpoint->media.rtp.engine);
00117       return -1;
00118    }
00119 
00120    ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_RTCP, 1);
00121    ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_NAT, session->endpoint->media.rtp.symmetric);
00122 
00123    if (!session->endpoint->media.rtp.ice_support && (ice = ast_rtp_instance_get_ice(session_media->rtp))) {
00124       ice->stop(session_media->rtp);
00125    }
00126 
00127    if (session->endpoint->dtmf == AST_SIP_DTMF_RFC_4733 || session->endpoint->dtmf == AST_SIP_DTMF_AUTO) {
00128       ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_RFC2833);
00129       ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_DTMF, 1);
00130    } else if (session->endpoint->dtmf == AST_SIP_DTMF_INBAND) {
00131       ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_INBAND);
00132    }
00133 
00134    if (!strcmp(session_media->stream_type, STR_AUDIO) &&
00135          (session->endpoint->media.tos_audio || session->endpoint->media.cos_video)) {
00136       ast_rtp_instance_set_qos(session_media->rtp, session->endpoint->media.tos_audio,
00137             session->endpoint->media.cos_audio, "SIP RTP Audio");
00138    } else if (!strcmp(session_media->stream_type, STR_VIDEO) &&
00139          (session->endpoint->media.tos_video || session->endpoint->media.cos_video)) {
00140       ast_rtp_instance_set_qos(session_media->rtp, session->endpoint->media.tos_video,
00141             session->endpoint->media.cos_video, "SIP RTP Video");
00142    }
00143 
00144    return 0;
00145 }
00146 
00147 static void get_codecs(struct ast_sip_session *session, const struct pjmedia_sdp_media *stream, struct ast_rtp_codecs *codecs,
00148        struct ast_sip_session_media *session_media)
00149 {
00150    pjmedia_sdp_attr *attr;
00151    pjmedia_sdp_rtpmap *rtpmap;
00152    pjmedia_sdp_fmtp fmtp;
00153    struct ast_format *format;
00154    int i, num = 0, tel_event = 0;
00155    char name[256];
00156    char media[20];
00157    char fmt_param[256];
00158 
00159    ast_rtp_codecs_payloads_initialize(codecs);
00160 
00161    /* Iterate through provided formats */
00162    for (i = 0; i < stream->desc.fmt_count; ++i) {
00163       /* The payload is kept as a string for things like t38 but for video it is always numerical */
00164       ast_rtp_codecs_payloads_set_m_type(codecs, NULL, pj_strtoul(&stream->desc.fmt[i]));
00165       /* Look for the optional rtpmap attribute */
00166       if (!(attr = pjmedia_sdp_media_find_attr2(stream, "rtpmap", &stream->desc.fmt[i]))) {
00167          continue;
00168       }
00169 
00170       /* Interpret the attribute as an rtpmap */
00171       if ((pjmedia_sdp_attr_to_rtpmap(session->inv_session->pool_prov, attr, &rtpmap)) != PJ_SUCCESS) {
00172          continue;
00173       }
00174 
00175       ast_copy_pj_str(name, &rtpmap->enc_name, sizeof(name));
00176                 if (strcmp(name,"telephone-event") == 0) {
00177                         tel_event++;
00178                 }
00179       ast_copy_pj_str(media, (pj_str_t*)&stream->desc.media, sizeof(media));
00180       ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, NULL, pj_strtoul(&stream->desc.fmt[i]),
00181                           media, name, 0, rtpmap->clock_rate);
00182       /* Look for an optional associated fmtp attribute */
00183       if (!(attr = pjmedia_sdp_media_find_attr2(stream, "fmtp", &rtpmap->pt))) {
00184          continue;
00185       }
00186 
00187       if ((pjmedia_sdp_attr_get_fmtp(attr, &fmtp)) == PJ_SUCCESS) {
00188          ast_copy_pj_str(fmt_param, &fmtp.fmt, sizeof(fmt_param));
00189          if (sscanf(fmt_param, "%30d", &num) != 1) {
00190             continue;
00191          }
00192 
00193          if ((format = ast_rtp_codecs_get_payload_format(codecs, num))) {
00194             struct ast_format *format_parsed;
00195 
00196             ast_copy_pj_str(fmt_param, &fmtp.fmt_param, sizeof(fmt_param));
00197 
00198             format_parsed = ast_format_parse_sdp_fmtp(format, fmt_param);
00199             if (format_parsed) {
00200                ast_rtp_codecs_payload_replace_format(codecs, num, format_parsed);
00201                ao2_ref(format_parsed, -1);
00202             }
00203 
00204             ao2_ref(format, -1);
00205          }
00206       }
00207    }
00208    if ((tel_event==0) && (session->endpoint->dtmf == AST_SIP_DTMF_AUTO)) {
00209                 ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_INBAND);
00210    }
00211    /* Get the packetization, if it exists */
00212    if ((attr = pjmedia_sdp_media_find_attr2(stream, "ptime", NULL))) {
00213       unsigned long framing = pj_strtoul(pj_strltrim(&attr->value));
00214       if (framing && session->endpoint->media.rtp.use_ptime) {
00215          ast_rtp_codecs_set_framing(codecs, framing);
00216       }
00217    }
00218 }
00219 
00220 static int set_caps(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
00221           const struct pjmedia_sdp_media *stream)
00222 {
00223    RAII_VAR(struct ast_format_cap *, caps, NULL, ao2_cleanup);
00224    RAII_VAR(struct ast_format_cap *, peer, NULL, ao2_cleanup);
00225    RAII_VAR(struct ast_format_cap *, joint, NULL, ao2_cleanup);
00226    enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
00227    struct ast_rtp_codecs codecs = AST_RTP_CODECS_NULL_INIT;
00228    int fmts = 0;
00229    int direct_media_enabled = !ast_sockaddr_isnull(&session_media->direct_media_addr) &&
00230       ast_format_cap_count(session->direct_media_cap);
00231    int dsp_features = 0;
00232 
00233    if (!(caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT)) ||
00234        !(peer = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT)) ||
00235        !(joint = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
00236       ast_log(LOG_ERROR, "Failed to allocate %s capabilities\n", session_media->stream_type);
00237       return -1;
00238    }
00239 
00240    /* get the endpoint capabilities */
00241    if (direct_media_enabled) {
00242       ast_format_cap_get_compatible(session->endpoint->media.codecs, session->direct_media_cap, caps);
00243       format_cap_only_type(caps, media_type);
00244    } else {
00245       ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, media_type);
00246    }
00247 
00248    /* get the capabilities on the peer */
00249    get_codecs(session, stream, &codecs,  session_media);
00250    ast_rtp_codecs_payload_formats(&codecs, peer, &fmts);
00251 
00252    /* get the joint capabilities between peer and endpoint */
00253    ast_format_cap_get_compatible(caps, peer, joint);
00254    if (!ast_format_cap_count(joint)) {
00255       struct ast_str *usbuf = ast_str_alloca(256);
00256       struct ast_str *thembuf = ast_str_alloca(256);
00257 
00258       ast_rtp_codecs_payloads_destroy(&codecs);
00259       ast_log(LOG_NOTICE, "No joint capabilities for '%s' media stream between our configuration(%s) and incoming SDP(%s)\n",
00260          session_media->stream_type,
00261          ast_format_cap_get_names(caps, &usbuf),
00262          ast_format_cap_get_names(peer, &thembuf));
00263       return -1;
00264    }
00265 
00266    ast_rtp_codecs_payloads_copy(&codecs, ast_rtp_instance_get_codecs(session_media->rtp),
00267                  session_media->rtp);
00268 
00269    ast_format_cap_append_from_cap(session->req_caps, joint, AST_MEDIA_TYPE_UNKNOWN);
00270 
00271    if (session->channel) {
00272       ast_channel_lock(session->channel);
00273       ast_format_cap_remove_by_type(caps, AST_MEDIA_TYPE_UNKNOWN);
00274       ast_format_cap_append_from_cap(caps, ast_channel_nativeformats(session->channel),
00275          AST_MEDIA_TYPE_UNKNOWN);
00276       ast_format_cap_remove_by_type(caps, media_type);
00277       ast_format_cap_append_from_cap(caps, joint, media_type);
00278 
00279       /*
00280        * Apply the new formats to the channel, potentially changing
00281        * raw read/write formats and translation path while doing so.
00282        */
00283       ast_channel_nativeformats_set(session->channel, caps);
00284       if (media_type == AST_MEDIA_TYPE_AUDIO) {
00285          ast_set_read_format(session->channel, ast_channel_readformat(session->channel));
00286          ast_set_write_format(session->channel, ast_channel_writeformat(session->channel));
00287       }
00288       if ((session->endpoint->dtmf == AST_SIP_DTMF_AUTO)
00289           && (ast_rtp_instance_dtmf_mode_get(session_media->rtp) == AST_RTP_DTMF_MODE_RFC2833)
00290           && (session->dsp)) {
00291          dsp_features = ast_dsp_get_features(session->dsp);
00292          dsp_features &= ~DSP_FEATURE_DIGIT_DETECT;
00293          if (dsp_features) {
00294             ast_dsp_set_features(session->dsp, dsp_features);
00295          } else {
00296             ast_dsp_free(session->dsp);
00297             session->dsp = NULL;
00298          }
00299       }
00300       ast_channel_unlock(session->channel);
00301    }
00302 
00303    ast_rtp_codecs_payloads_destroy(&codecs);
00304    return 0;
00305 }
00306 
00307 static pjmedia_sdp_attr* generate_rtpmap_attr(pjmedia_sdp_media *media, pj_pool_t *pool, int rtp_code,
00308                      int asterisk_format, struct ast_format *format, int code)
00309 {
00310    pjmedia_sdp_rtpmap rtpmap;
00311    pjmedia_sdp_attr *attr = NULL;
00312    char tmp[64];
00313 
00314    snprintf(tmp, sizeof(tmp), "%d", rtp_code);
00315    pj_strdup2(pool, &media->desc.fmt[media->desc.fmt_count++], tmp);
00316    rtpmap.pt = media->desc.fmt[media->desc.fmt_count - 1];
00317    rtpmap.clock_rate = ast_rtp_lookup_sample_rate2(asterisk_format, format, code);
00318    pj_strdup2(pool, &rtpmap.enc_name, ast_rtp_lookup_mime_subtype2(asterisk_format, format, code, 0));
00319    rtpmap.param.slen = 0;
00320    rtpmap.param.ptr = NULL;
00321 
00322    pjmedia_sdp_rtpmap_to_attr(pool, &rtpmap, &attr);
00323 
00324    return attr;
00325 }
00326 
00327 static pjmedia_sdp_attr* generate_fmtp_attr(pj_pool_t *pool, struct ast_format *format, int rtp_code)
00328 {
00329    struct ast_str *fmtp0 = ast_str_alloca(256);
00330    pj_str_t fmtp1;
00331    pjmedia_sdp_attr *attr = NULL;
00332    char *tmp;
00333 
00334    ast_format_generate_sdp_fmtp(format, rtp_code, &fmtp0);
00335    if (ast_str_strlen(fmtp0)) {
00336       tmp = ast_str_buffer(fmtp0) + ast_str_strlen(fmtp0) - 1;
00337       /* remove any carriage return line feeds */
00338       while (*tmp == '\r' || *tmp == '\n') --tmp;
00339       *++tmp = '\0';
00340       /* ast...generate gives us everything, just need value */
00341       tmp = strchr(ast_str_buffer(fmtp0), ':');
00342       if (tmp && tmp + 1) {
00343          fmtp1 = pj_str(tmp + 1);
00344       } else {
00345          fmtp1 = pj_str(ast_str_buffer(fmtp0));
00346       }
00347       attr = pjmedia_sdp_attr_create(pool, "fmtp", &fmtp1);
00348    }
00349    return attr;
00350 }
00351 
00352 /*! \brief Function which adds ICE attributes to a media stream */
00353 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)
00354 {
00355    struct ast_rtp_engine_ice *ice;
00356    struct ao2_container *candidates;
00357    const char *username, *password;
00358    pj_str_t stmp;
00359    pjmedia_sdp_attr *attr;
00360    struct ao2_iterator it_candidates;
00361    struct ast_rtp_engine_ice_candidate *candidate;
00362 
00363    if (!session->endpoint->media.rtp.ice_support || !(ice = ast_rtp_instance_get_ice(session_media->rtp)) ||
00364       !(candidates = ice->get_local_candidates(session_media->rtp))) {
00365       return;
00366    }
00367 
00368    if ((username = ice->get_ufrag(session_media->rtp))) {
00369       attr = pjmedia_sdp_attr_create(pool, "ice-ufrag", pj_cstr(&stmp, username));
00370       media->attr[media->attr_count++] = attr;
00371    }
00372 
00373    if ((password = ice->get_password(session_media->rtp))) {
00374       attr = pjmedia_sdp_attr_create(pool, "ice-pwd", pj_cstr(&stmp, password));
00375       media->attr[media->attr_count++] = attr;
00376    }
00377 
00378    it_candidates = ao2_iterator_init(candidates, 0);
00379    for (; (candidate = ao2_iterator_next(&it_candidates)); ao2_ref(candidate, -1)) {
00380       struct ast_str *attr_candidate = ast_str_create(128);
00381 
00382       ast_str_set(&attr_candidate, -1, "%s %u %s %d %s ", candidate->foundation, candidate->id, candidate->transport,
00383                candidate->priority, ast_sockaddr_stringify_addr_remote(&candidate->address));
00384       ast_str_append(&attr_candidate, -1, "%s typ ", ast_sockaddr_stringify_port(&candidate->address));
00385 
00386       switch (candidate->type) {
00387          case AST_RTP_ICE_CANDIDATE_TYPE_HOST:
00388             ast_str_append(&attr_candidate, -1, "host");
00389             break;
00390          case AST_RTP_ICE_CANDIDATE_TYPE_SRFLX:
00391             ast_str_append(&attr_candidate, -1, "srflx");
00392             break;
00393          case AST_RTP_ICE_CANDIDATE_TYPE_RELAYED:
00394             ast_str_append(&attr_candidate, -1, "relay");
00395             break;
00396       }
00397 
00398       if (!ast_sockaddr_isnull(&candidate->relay_address)) {
00399          ast_str_append(&attr_candidate, -1, " raddr %s rport", ast_sockaddr_stringify_addr_remote(&candidate->relay_address));
00400          ast_str_append(&attr_candidate, -1, " %s", ast_sockaddr_stringify_port(&candidate->relay_address));
00401       }
00402 
00403       attr = pjmedia_sdp_attr_create(pool, "candidate", pj_cstr(&stmp, ast_str_buffer(attr_candidate)));
00404       media->attr[media->attr_count++] = attr;
00405 
00406       ast_free(attr_candidate);
00407    }
00408 
00409    ao2_iterator_destroy(&it_candidates);
00410    ao2_ref(candidates, -1);
00411 }
00412 
00413 /*! \brief Function which processes ICE attributes in an audio stream */
00414 static void process_ice_attributes(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
00415                const struct pjmedia_sdp_session *remote, const struct pjmedia_sdp_media *remote_stream)
00416 {
00417    struct ast_rtp_engine_ice *ice;
00418    const pjmedia_sdp_attr *attr;
00419    char attr_value[256];
00420    unsigned int attr_i;
00421 
00422    /* If ICE support is not enabled or available exit early */
00423    if (!session->endpoint->media.rtp.ice_support || !(ice = ast_rtp_instance_get_ice(session_media->rtp))) {
00424       return;
00425    }
00426 
00427    attr = pjmedia_sdp_media_find_attr2(remote_stream, "ice-ufrag", NULL);
00428    if (!attr) {
00429       attr = pjmedia_sdp_attr_find2(remote->attr_count, remote->attr, "ice-ufrag", NULL);
00430    }
00431    if (attr) {
00432       ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
00433       ice->set_authentication(session_media->rtp, attr_value, NULL);
00434    } else {
00435       return;
00436    }
00437 
00438    attr = pjmedia_sdp_media_find_attr2(remote_stream, "ice-pwd", NULL);
00439    if (!attr) {
00440       attr = pjmedia_sdp_attr_find2(remote->attr_count, remote->attr, "ice-pwd", NULL);
00441    }
00442    if (attr) {
00443       ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
00444       ice->set_authentication(session_media->rtp, NULL, attr_value);
00445    } else {
00446       return;
00447    }
00448 
00449    if (pjmedia_sdp_media_find_attr2(remote_stream, "ice-lite", NULL)) {
00450       ice->ice_lite(session_media->rtp);
00451    }
00452 
00453    /* Find all of the candidates */
00454    for (attr_i = 0; attr_i < remote_stream->attr_count; ++attr_i) {
00455       char foundation[32], transport[32], address[PJ_INET6_ADDRSTRLEN + 1], cand_type[6], relay_address[PJ_INET6_ADDRSTRLEN + 1] = "";
00456       unsigned int port, relay_port = 0;
00457       struct ast_rtp_engine_ice_candidate candidate = { 0, };
00458 
00459       attr = remote_stream->attr[attr_i];
00460 
00461       /* If this is not a candidate line skip it */
00462       if (pj_strcmp2(&attr->name, "candidate")) {
00463          continue;
00464       }
00465 
00466       ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
00467 
00468       if (sscanf(attr_value, "%31s %30u %31s %30u %46s %30u typ %5s %*s %23s %*s %30u", foundation, &candidate.id, transport,
00469          (unsigned *)&candidate.priority, address, &port, cand_type, relay_address, &relay_port) < 7) {
00470          /* Candidate did not parse properly */
00471          continue;
00472       }
00473 
00474       candidate.foundation = foundation;
00475       candidate.transport = transport;
00476 
00477       ast_sockaddr_parse(&candidate.address, address, PARSE_PORT_FORBID);
00478       ast_sockaddr_set_port(&candidate.address, port);
00479 
00480       if (!strcasecmp(cand_type, "host")) {
00481          candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
00482       } else if (!strcasecmp(cand_type, "srflx")) {
00483          candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
00484       } else if (!strcasecmp(cand_type, "relay")) {
00485          candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
00486       } else {
00487          continue;
00488       }
00489 
00490       if (!ast_strlen_zero(relay_address)) {
00491          ast_sockaddr_parse(&candidate.relay_address, relay_address, PARSE_PORT_FORBID);
00492       }
00493 
00494       if (relay_port) {
00495          ast_sockaddr_set_port(&candidate.relay_address, relay_port);
00496       }
00497 
00498       ice->add_remote_candidate(session_media->rtp, &candidate);
00499    }
00500 
00501    ice->set_role(session_media->rtp, pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_TRUE ?
00502       AST_RTP_ICE_ROLE_CONTROLLING : AST_RTP_ICE_ROLE_CONTROLLED);
00503    ice->start(session_media->rtp);
00504 }
00505 
00506 /*! \brief figure out if media stream has crypto lines for sdes */
00507 static int media_stream_has_crypto(const struct pjmedia_sdp_media *stream)
00508 {
00509    int i;
00510 
00511    for (i = 0; i < stream->attr_count; i++) {
00512       pjmedia_sdp_attr *attr;
00513 
00514       /* check the stream for the required crypto attribute */
00515       attr = stream->attr[i];
00516       if (pj_strcmp2(&attr->name, "crypto")) {
00517          continue;
00518       }
00519 
00520       return 1;
00521    }
00522 
00523    return 0;
00524 }
00525 
00526 /*! \brief figure out media transport encryption type from the media transport string */
00527 static enum ast_sip_session_media_encryption get_media_encryption_type(pj_str_t transport,
00528    const struct pjmedia_sdp_media *stream, unsigned int *optimistic)
00529 {
00530    RAII_VAR(char *, transport_str, ast_strndup(transport.ptr, transport.slen), ast_free);
00531 
00532    *optimistic = 0;
00533 
00534    if (strstr(transport_str, "UDP/TLS")) {
00535       return AST_SIP_MEDIA_ENCRYPT_DTLS;
00536    } else if (strstr(transport_str, "SAVP")) {
00537       return AST_SIP_MEDIA_ENCRYPT_SDES;
00538    } else if (media_stream_has_crypto(stream)) {
00539       *optimistic = 1;
00540       return AST_SIP_MEDIA_ENCRYPT_SDES;
00541    } else {
00542       return AST_SIP_MEDIA_ENCRYPT_NONE;
00543    }
00544 }
00545 
00546 /*!
00547  * \brief Checks whether the encryption offered in SDP is compatible with the endpoint's configuration
00548  * \internal
00549  *
00550  * \param endpoint_encryption Media encryption configured for the endpoint
00551  * \param stream pjmedia_sdp_media stream description
00552  *
00553  * \retval AST_SIP_MEDIA_TRANSPORT_INVALID on encryption mismatch
00554  * \retval The encryption requested in the SDP
00555  */
00556 static enum ast_sip_session_media_encryption check_endpoint_media_transport(
00557    struct ast_sip_endpoint *endpoint,
00558    const struct pjmedia_sdp_media *stream)
00559 {
00560    enum ast_sip_session_media_encryption incoming_encryption;
00561    char transport_end = stream->desc.transport.ptr[stream->desc.transport.slen - 1];
00562    unsigned int optimistic;
00563 
00564    if ((transport_end == 'F' && !endpoint->media.rtp.use_avpf)
00565       || (transport_end != 'F' && endpoint->media.rtp.use_avpf)) {
00566       return AST_SIP_MEDIA_TRANSPORT_INVALID;
00567    }
00568 
00569    incoming_encryption = get_media_encryption_type(stream->desc.transport, stream, &optimistic);
00570 
00571    if (incoming_encryption == endpoint->media.rtp.encryption) {
00572       return incoming_encryption;
00573    }
00574 
00575    if (endpoint->media.rtp.force_avp ||
00576       endpoint->media.rtp.encryption_optimistic) {
00577       return incoming_encryption;
00578    }
00579 
00580    /* If an optimistic offer has been made but encryption is not enabled consider it as having
00581     * no offer of crypto at all instead of invalid so the session proceeds.
00582     */
00583    if (optimistic) {
00584       return AST_SIP_MEDIA_ENCRYPT_NONE;
00585    }
00586 
00587    return AST_SIP_MEDIA_TRANSPORT_INVALID;
00588 }
00589 
00590 static int setup_srtp(struct ast_sip_session_media *session_media)
00591 {
00592    if (!session_media->srtp) {
00593       session_media->srtp = ast_sdp_srtp_alloc();
00594       if (!session_media->srtp) {
00595          return -1;
00596       }
00597    }
00598 
00599    if (!session_media->srtp->crypto) {
00600       session_media->srtp->crypto = ast_sdp_crypto_alloc();
00601       if (!session_media->srtp->crypto) {
00602          return -1;
00603       }
00604    }
00605 
00606    return 0;
00607 }
00608 
00609 static int setup_dtls_srtp(struct ast_sip_session *session,
00610    struct ast_sip_session_media *session_media)
00611 {
00612    struct ast_rtp_engine_dtls *dtls;
00613 
00614    if (!session->endpoint->media.rtp.dtls_cfg.enabled || !session_media->rtp) {
00615       return -1;
00616    }
00617 
00618    dtls = ast_rtp_instance_get_dtls(session_media->rtp);
00619    if (!dtls) {
00620       return -1;
00621    }
00622 
00623    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);
00624    if (dtls->set_configuration(session_media->rtp, &session->endpoint->media.rtp.dtls_cfg)) {
00625       ast_log(LOG_ERROR, "Attempted to set an invalid DTLS-SRTP configuration on RTP instance '%p'\n",
00626          session_media->rtp);
00627       return -1;
00628    }
00629 
00630    if (setup_srtp(session_media)) {
00631       return -1;
00632    }
00633    return 0;
00634 }
00635 
00636 static void apply_dtls_attrib(struct ast_sip_session_media *session_media,
00637    pjmedia_sdp_attr *attr)
00638 {
00639    struct ast_rtp_engine_dtls *dtls = ast_rtp_instance_get_dtls(session_media->rtp);
00640    pj_str_t *value;
00641 
00642    if (!attr->value.ptr) {
00643       return;
00644    }
00645 
00646    value = pj_strtrim(&attr->value);
00647 
00648    if (!pj_strcmp2(&attr->name, "setup")) {
00649       if (!pj_stricmp2(value, "active")) {
00650          dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_ACTIVE);
00651       } else if (!pj_stricmp2(value, "passive")) {
00652          dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_PASSIVE);
00653       } else if (!pj_stricmp2(value, "actpass")) {
00654          dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_ACTPASS);
00655       } else if (!pj_stricmp2(value, "holdconn")) {
00656          dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_HOLDCONN);
00657       } else {
00658          ast_log(LOG_WARNING, "Unsupported setup attribute value '%*s'\n", (int)value->slen, value->ptr);
00659       }
00660    } else if (!pj_strcmp2(&attr->name, "connection")) {
00661       if (!pj_stricmp2(value, "new")) {
00662          dtls->reset(session_media->rtp);
00663       } else if (!pj_stricmp2(value, "existing")) {
00664          /* Do nothing */
00665       } else {
00666          ast_log(LOG_WARNING, "Unsupported connection attribute value '%*s'\n", (int)value->slen, value->ptr);
00667       }
00668    } else if (!pj_strcmp2(&attr->name, "fingerprint")) {
00669       char hash_value[256], hash[32];
00670       char fingerprint_text[value->slen + 1];
00671       ast_copy_pj_str(fingerprint_text, value, sizeof(fingerprint_text));
00672          if (sscanf(fingerprint_text, "%31s %255s", hash, hash_value) == 2) {
00673          if (!strcasecmp(hash, "sha-1")) {
00674             dtls->set_fingerprint(session_media->rtp, AST_RTP_DTLS_HASH_SHA1, hash_value);
00675          } else if (!strcasecmp(hash, "sha-256")) {
00676             dtls->set_fingerprint(session_media->rtp, AST_RTP_DTLS_HASH_SHA256, hash_value);
00677          } else {
00678             ast_log(LOG_WARNING, "Unsupported fingerprint hash type '%s'\n",
00679             hash);
00680          }
00681       }
00682    }
00683 }
00684 
00685 static int parse_dtls_attrib(struct ast_sip_session_media *session_media,
00686    const struct pjmedia_sdp_session *sdp,
00687    const struct pjmedia_sdp_media *stream)
00688 {
00689    int i;
00690 
00691    for (i = 0; i < sdp->attr_count; i++) {
00692       apply_dtls_attrib(session_media, sdp->attr[i]);
00693    }
00694 
00695    for (i = 0; i < stream->attr_count; i++) {
00696       apply_dtls_attrib(session_media, stream->attr[i]);
00697    }
00698 
00699    ast_set_flag(session_media->srtp, AST_SRTP_CRYPTO_OFFER_OK);
00700 
00701    return 0;
00702 }
00703 
00704 static int setup_sdes_srtp(struct ast_sip_session_media *session_media,
00705    const struct pjmedia_sdp_media *stream)
00706 {
00707    int i;
00708 
00709    for (i = 0; i < stream->attr_count; i++) {
00710       pjmedia_sdp_attr *attr;
00711       RAII_VAR(char *, crypto_str, NULL, ast_free);
00712 
00713       /* check the stream for the required crypto attribute */
00714       attr = stream->attr[i];
00715       if (pj_strcmp2(&attr->name, "crypto")) {
00716          continue;
00717       }
00718 
00719       crypto_str = ast_strndup(attr->value.ptr, attr->value.slen);
00720       if (!crypto_str) {
00721          return -1;
00722       }
00723 
00724       if (setup_srtp(session_media)) {
00725          return -1;
00726       }
00727 
00728       if (!ast_sdp_crypto_process(session_media->rtp, session_media->srtp, crypto_str)) {
00729          /* found a valid crypto attribute */
00730          return 0;
00731       }
00732 
00733       ast_debug(1, "Ignoring crypto offer with unsupported parameters: %s\n", crypto_str);
00734    }
00735 
00736    /* no usable crypto attributes found */
00737    return -1;
00738 }
00739 
00740 static int setup_media_encryption(struct ast_sip_session *session,
00741    struct ast_sip_session_media *session_media,
00742    const struct pjmedia_sdp_session *sdp,
00743    const struct pjmedia_sdp_media *stream)
00744 {
00745    switch (session_media->encryption) {
00746    case AST_SIP_MEDIA_ENCRYPT_SDES:
00747       if (setup_sdes_srtp(session_media, stream)) {
00748          return -1;
00749       }
00750       break;
00751    case AST_SIP_MEDIA_ENCRYPT_DTLS:
00752       if (setup_dtls_srtp(session, session_media)) {
00753          return -1;
00754       }
00755       if (parse_dtls_attrib(session_media, sdp, stream)) {
00756          return -1;
00757       }
00758       break;
00759    case AST_SIP_MEDIA_TRANSPORT_INVALID:
00760    case AST_SIP_MEDIA_ENCRYPT_NONE:
00761       break;
00762    }
00763 
00764    return 0;
00765 }
00766 
00767 /*! \brief Function which negotiates an incoming media stream */
00768 static int negotiate_incoming_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
00769                 const struct pjmedia_sdp_session *sdp, const struct pjmedia_sdp_media *stream)
00770 {
00771    char host[NI_MAXHOST];
00772    RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
00773    enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
00774    enum ast_sip_session_media_encryption encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
00775    int res;
00776 
00777    /* If port is 0, ignore this media stream */
00778    if (!stream->desc.port) {
00779       ast_debug(3, "Media stream '%s' is already declined\n", session_media->stream_type);
00780       return 0;
00781    }
00782 
00783    /* If no type formats have been configured reject this stream */
00784    if (!ast_format_cap_has_type(session->endpoint->media.codecs, media_type)) {
00785       ast_debug(3, "Endpoint has no codecs for media type '%s', declining stream\n", session_media->stream_type);
00786       return 0;
00787    }
00788 
00789    /* Ensure incoming transport is compatible with the endpoint's configuration */
00790    if (!session->endpoint->media.rtp.use_received_transport) {
00791       encryption = check_endpoint_media_transport(session->endpoint, stream);
00792 
00793       if (encryption == AST_SIP_MEDIA_TRANSPORT_INVALID) {
00794          return -1;
00795       }
00796    }
00797 
00798    ast_copy_pj_str(host, stream->conn ? &stream->conn->addr : &sdp->conn->addr, sizeof(host));
00799 
00800    /* Ensure that the address provided is valid */
00801    if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
00802       /* The provided host was actually invalid so we error out this negotiation */
00803       return -1;
00804    }
00805 
00806    /* Using the connection information create an appropriate RTP instance */
00807    if (!session_media->rtp && create_rtp(session, session_media, ast_sockaddr_is_ipv6(addrs))) {
00808       return -1;
00809    }
00810 
00811    res = setup_media_encryption(session, session_media, sdp, stream);
00812    if (res) {
00813       if (!session->endpoint->media.rtp.encryption_optimistic) {
00814          /* If optimistic encryption is disabled and crypto should have been enabled
00815           * but was not this session must fail.
00816           */
00817          return -1;
00818       }
00819       /* There is no encryption, sad. */
00820       session_media->encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
00821    }
00822 
00823    /* If we've been explicitly configured to use the received transport OR if
00824     * encryption is on and crypto is present use the received transport.
00825     * This is done in case of optimistic because it may come in as RTP/AVP or RTP/SAVP depending
00826     * on the configuration of the remote endpoint (optimistic themselves or mandatory).
00827     */
00828    if ((session->endpoint->media.rtp.use_received_transport) ||
00829       ((encryption == AST_SIP_MEDIA_ENCRYPT_SDES) && !res)) {
00830       pj_strdup(session->inv_session->pool, &session_media->transport, &stream->desc.transport);
00831    }
00832 
00833    if (set_caps(session, session_media, stream)) {
00834       return 0;
00835    }
00836    return 1;
00837 }
00838 
00839 static int add_crypto_to_stream(struct ast_sip_session *session,
00840    struct ast_sip_session_media *session_media,
00841    pj_pool_t *pool, pjmedia_sdp_media *media)
00842 {
00843    pj_str_t stmp;
00844    pjmedia_sdp_attr *attr;
00845    enum ast_rtp_dtls_hash hash;
00846    const char *crypto_attribute;
00847    struct ast_rtp_engine_dtls *dtls;
00848    static const pj_str_t STR_NEW = { "new", 3 };
00849    static const pj_str_t STR_EXISTING = { "existing", 8 };
00850    static const pj_str_t STR_ACTIVE = { "active", 6 };
00851    static const pj_str_t STR_PASSIVE = { "passive", 7 };
00852    static const pj_str_t STR_ACTPASS = { "actpass", 7 };
00853    static const pj_str_t STR_HOLDCONN = { "holdconn", 8 };
00854 
00855    switch (session_media->encryption) {
00856    case AST_SIP_MEDIA_ENCRYPT_NONE:
00857    case AST_SIP_MEDIA_TRANSPORT_INVALID:
00858       break;
00859    case AST_SIP_MEDIA_ENCRYPT_SDES:
00860       if (!session_media->srtp) {
00861          session_media->srtp = ast_sdp_srtp_alloc();
00862          if (!session_media->srtp) {
00863             return -1;
00864          }
00865       }
00866 
00867       crypto_attribute = ast_sdp_srtp_get_attrib(session_media->srtp,
00868          0 /* DTLS running? No */,
00869          session->endpoint->media.rtp.srtp_tag_32 /* 32 byte tag length? */);
00870       if (!crypto_attribute) {
00871          /* No crypto attribute to add, bad news */
00872          return -1;
00873       }
00874 
00875       attr = pjmedia_sdp_attr_create(pool, "crypto", pj_cstr(&stmp, crypto_attribute));
00876       media->attr[media->attr_count++] = attr;
00877       break;
00878    case AST_SIP_MEDIA_ENCRYPT_DTLS:
00879       if (setup_dtls_srtp(session, session_media)) {
00880          return -1;
00881       }
00882 
00883       dtls = ast_rtp_instance_get_dtls(session_media->rtp);
00884       if (!dtls) {
00885          return -1;
00886       }
00887 
00888       switch (dtls->get_connection(session_media->rtp)) {
00889       case AST_RTP_DTLS_CONNECTION_NEW:
00890          attr = pjmedia_sdp_attr_create(pool, "connection", &STR_NEW);
00891          media->attr[media->attr_count++] = attr;
00892          break;
00893       case AST_RTP_DTLS_CONNECTION_EXISTING:
00894          attr = pjmedia_sdp_attr_create(pool, "connection", &STR_EXISTING);
00895          media->attr[media->attr_count++] = attr;
00896          break;
00897       default:
00898          break;
00899       }
00900 
00901       switch (dtls->get_setup(session_media->rtp)) {
00902       case AST_RTP_DTLS_SETUP_ACTIVE:
00903          attr = pjmedia_sdp_attr_create(pool, "setup", &STR_ACTIVE);
00904          media->attr[media->attr_count++] = attr;
00905          break;
00906       case AST_RTP_DTLS_SETUP_PASSIVE:
00907          attr = pjmedia_sdp_attr_create(pool, "setup", &STR_PASSIVE);
00908          media->attr[media->attr_count++] = attr;
00909          break;
00910       case AST_RTP_DTLS_SETUP_ACTPASS:
00911          attr = pjmedia_sdp_attr_create(pool, "setup", &STR_ACTPASS);
00912          media->attr[media->attr_count++] = attr;
00913          break;
00914       case AST_RTP_DTLS_SETUP_HOLDCONN:
00915          attr = pjmedia_sdp_attr_create(pool, "setup", &STR_HOLDCONN);
00916          media->attr[media->attr_count++] = attr;
00917          break;
00918       default:
00919          break;
00920       }
00921 
00922       hash = dtls->get_fingerprint_hash(session_media->rtp);
00923       crypto_attribute = dtls->get_fingerprint(session_media->rtp);
00924       if (crypto_attribute && (hash == AST_RTP_DTLS_HASH_SHA1 || hash == AST_RTP_DTLS_HASH_SHA256)) {
00925          RAII_VAR(struct ast_str *, fingerprint, ast_str_create(64), ast_free);
00926          if (!fingerprint) {
00927             return -1;
00928          }
00929 
00930          if (hash == AST_RTP_DTLS_HASH_SHA1) {
00931             ast_str_set(&fingerprint, 0, "SHA-1 %s", crypto_attribute);
00932          } else {
00933             ast_str_set(&fingerprint, 0, "SHA-256 %s", crypto_attribute);
00934          }
00935 
00936          attr = pjmedia_sdp_attr_create(pool, "fingerprint", pj_cstr(&stmp, ast_str_buffer(fingerprint)));
00937          media->attr[media->attr_count++] = attr;
00938       }
00939       break;
00940    }
00941 
00942    return 0;
00943 }
00944 
00945 /*! \brief Function which creates an outgoing stream */
00946 static int create_outgoing_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
00947                   struct pjmedia_sdp_session *sdp)
00948 {
00949    pj_pool_t *pool = session->inv_session->pool_prov;
00950    static const pj_str_t STR_IN = { "IN", 2 };
00951    static const pj_str_t STR_IP4 = { "IP4", 3};
00952    static const pj_str_t STR_IP6 = { "IP6", 3};
00953    static const pj_str_t STR_SENDRECV = { "sendrecv", 8 };
00954    static const pj_str_t STR_SENDONLY = { "sendonly", 8 };
00955    pjmedia_sdp_media *media;
00956    char hostip[PJ_INET6_ADDRSTRLEN+2];
00957    struct ast_sockaddr addr;
00958    char tmp[512];
00959    pj_str_t stmp;
00960    pjmedia_sdp_attr *attr;
00961    int index = 0;
00962    int noncodec = (session->endpoint->dtmf == AST_SIP_DTMF_RFC_4733 || session->endpoint->dtmf == AST_SIP_DTMF_AUTO) ? AST_RTP_DTMF : 0;
00963    int min_packet_size = 0, max_packet_size = 0;
00964    int rtp_code;
00965    RAII_VAR(struct ast_format_cap *, caps, NULL, ao2_cleanup);
00966    enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
00967    int use_override_prefs = ast_format_cap_count(session->req_caps);
00968 
00969    int direct_media_enabled = !ast_sockaddr_isnull(&session_media->direct_media_addr) &&
00970       ast_format_cap_count(session->direct_media_cap);
00971 
00972    if ((use_override_prefs && !ast_format_cap_has_type(session->req_caps, media_type)) ||
00973        (!use_override_prefs && !ast_format_cap_has_type(session->endpoint->media.codecs, media_type))) {
00974       /* If no type formats are configured don't add a stream */
00975       return 0;
00976    } else if (!session_media->rtp && create_rtp(session, session_media, session->endpoint->media.rtp.ipv6)) {
00977       return -1;
00978    }
00979 
00980    if (!(media = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_media))) ||
00981       !(media->conn = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_conn)))) {
00982       return -1;
00983    }
00984 
00985    if (add_crypto_to_stream(session, session_media, pool, media)) {
00986       return -1;
00987    }
00988 
00989    media->desc.media = pj_str(session_media->stream_type);
00990    if (pj_strlen(&session_media->transport)) {
00991       /* If a transport has already been specified use it */
00992       media->desc.transport = session_media->transport;
00993    } else {
00994       media->desc.transport = pj_str(ast_sdp_get_rtp_profile(
00995          /* Optimistic encryption places crypto in the normal RTP/AVP profile */
00996          !session->endpoint->media.rtp.encryption_optimistic &&
00997             (session_media->encryption == AST_SIP_MEDIA_ENCRYPT_SDES),
00998          session_media->rtp, session->endpoint->media.rtp.use_avpf,
00999          session->endpoint->media.rtp.force_avp));
01000    }
01001 
01002    /* Add connection level details */
01003    if (direct_media_enabled) {
01004       ast_copy_string(hostip, ast_sockaddr_stringify_fmt(&session_media->direct_media_addr, AST_SOCKADDR_STR_ADDR), sizeof(hostip));
01005    } else if (ast_strlen_zero(session->endpoint->media.address)) {
01006       pj_sockaddr localaddr;
01007 
01008       if (pj_gethostip(session->endpoint->media.rtp.ipv6 ? pj_AF_INET6() : pj_AF_INET(), &localaddr)) {
01009          return -1;
01010       }
01011       pj_sockaddr_print(&localaddr, hostip, sizeof(hostip), 2);
01012    } else {
01013       ast_copy_string(hostip, session->endpoint->media.address, sizeof(hostip));
01014    }
01015 
01016    media->conn->net_type = STR_IN;
01017    media->conn->addr_type = session->endpoint->media.rtp.ipv6 ? STR_IP6 : STR_IP4;
01018    pj_strdup2(pool, &media->conn->addr, hostip);
01019    ast_rtp_instance_get_local_address(session_media->rtp, &addr);
01020    media->desc.port = direct_media_enabled ? ast_sockaddr_port(&session_media->direct_media_addr) : (pj_uint16_t) ast_sockaddr_port(&addr);
01021    media->desc.port_count = 1;
01022 
01023    /* Add ICE attributes and candidates */
01024    add_ice_to_stream(session, session_media, pool, media);
01025 
01026    if (!(caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
01027       ast_log(LOG_ERROR, "Failed to allocate %s capabilities\n", session_media->stream_type);
01028       return -1;
01029    }
01030 
01031    if (direct_media_enabled) {
01032       ast_format_cap_get_compatible(session->endpoint->media.codecs, session->direct_media_cap, caps);
01033    } else if (!ast_format_cap_count(session->req_caps) ||
01034       !ast_format_cap_iscompatible(session->req_caps, session->endpoint->media.codecs)) {
01035       ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, media_type);
01036    } else {
01037       ast_format_cap_append_from_cap(caps, session->req_caps, media_type);
01038    }
01039 
01040    for (index = 0; index < ast_format_cap_count(caps); ++index) {
01041       struct ast_format *format = ast_format_cap_get_format(caps, index);
01042 
01043       if (ast_format_get_type(format) != media_type) {
01044          ao2_ref(format, -1);
01045          continue;
01046       }
01047 
01048       if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(session_media->rtp), 1, format, 0)) == -1) {
01049          ast_log(LOG_WARNING,"Unable to get rtp codec payload code for %s\n", ast_format_get_name(format));
01050          ao2_ref(format, -1);
01051          continue;
01052       }
01053 
01054       if (!(attr = generate_rtpmap_attr(media, pool, rtp_code, 1, format, 0))) {
01055          ao2_ref(format, -1);
01056          continue;
01057       }
01058       media->attr[media->attr_count++] = attr;
01059 
01060       if ((attr = generate_fmtp_attr(pool, format, rtp_code))) {
01061          media->attr[media->attr_count++] = attr;
01062       }
01063 
01064       if (ast_format_get_maximum_ms(format) &&
01065          ((ast_format_get_maximum_ms(format) < max_packet_size) || !max_packet_size)) {
01066          max_packet_size = ast_format_get_maximum_ms(format);
01067       }
01068       ao2_ref(format, -1);
01069    }
01070 
01071    /* Add non-codec formats */
01072    if (media_type != AST_MEDIA_TYPE_VIDEO) {
01073       for (index = 1LL; index <= AST_RTP_MAX; index <<= 1) {
01074          if (!(noncodec & index) || (rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(session_media->rtp),
01075                                     0, NULL, index)) == -1) {
01076             continue;
01077          }
01078 
01079          if (!(attr = generate_rtpmap_attr(media, pool, rtp_code, 0, NULL, index))) {
01080             continue;
01081          }
01082 
01083          media->attr[media->attr_count++] = attr;
01084 
01085          if (index == AST_RTP_DTMF) {
01086             snprintf(tmp, sizeof(tmp), "%d 0-16", rtp_code);
01087             attr = pjmedia_sdp_attr_create(pool, "fmtp", pj_cstr(&stmp, tmp));
01088             media->attr[media->attr_count++] = attr;
01089          }
01090       }
01091    }
01092 
01093    /* If no formats were actually added to the media stream don't add it to the SDP */
01094    if (!media->desc.fmt_count) {
01095       return 1;
01096    }
01097 
01098    /* If ptime is set add it as an attribute */
01099    min_packet_size = ast_rtp_codecs_get_framing(ast_rtp_instance_get_codecs(session_media->rtp));
01100    if (!min_packet_size) {
01101       min_packet_size = ast_format_cap_get_framing(caps);
01102    }
01103    if (min_packet_size) {
01104       snprintf(tmp, sizeof(tmp), "%d", min_packet_size);
01105       attr = pjmedia_sdp_attr_create(pool, "ptime", pj_cstr(&stmp, tmp));
01106       media->attr[media->attr_count++] = attr;
01107    }
01108 
01109    if (max_packet_size) {
01110       snprintf(tmp, sizeof(tmp), "%d", max_packet_size);
01111       attr = pjmedia_sdp_attr_create(pool, "maxptime", pj_cstr(&stmp, tmp));
01112       media->attr[media->attr_count++] = attr;
01113    }
01114 
01115    /* Add the sendrecv attribute - we purposely don't keep track because pjmedia-sdp will automatically change our offer for us */
01116    attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr);
01117    attr->name = !session_media->locally_held ? STR_SENDRECV : STR_SENDONLY;
01118    media->attr[media->attr_count++] = attr;
01119 
01120    /* Add the media stream to the SDP */
01121    sdp->media[sdp->media_count++] = media;
01122 
01123    return 1;
01124 }
01125 
01126 static int apply_negotiated_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
01127                    const struct pjmedia_sdp_session *local, const struct pjmedia_sdp_media *local_stream,
01128                    const struct pjmedia_sdp_session *remote, const struct pjmedia_sdp_media *remote_stream)
01129 {
01130    RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
01131    enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
01132    char host[NI_MAXHOST];
01133    int fdno, res;
01134 
01135    if (!session->channel) {
01136       return 1;
01137    }
01138 
01139    if (!local_stream->desc.port || !remote_stream->desc.port) {
01140       return 1;
01141    }
01142 
01143    /* Ensure incoming transport is compatible with the endpoint's configuration */
01144    if (!session->endpoint->media.rtp.use_received_transport &&
01145       check_endpoint_media_transport(session->endpoint, remote_stream) == AST_SIP_MEDIA_TRANSPORT_INVALID) {
01146       return -1;
01147    }
01148 
01149    /* Create an RTP instance if need be */
01150    if (!session_media->rtp && create_rtp(session, session_media, session->endpoint->media.rtp.ipv6)) {
01151       return -1;
01152    }
01153 
01154    res = setup_media_encryption(session, session_media, remote, remote_stream);
01155    if (!session->endpoint->media.rtp.encryption_optimistic && res) {
01156       /* If optimistic encryption is disabled and crypto should have been enabled but was not
01157        * this session must fail.
01158        */
01159       return -1;
01160    }
01161 
01162    if (!remote_stream->conn && !remote->conn) {
01163       return 1;
01164    }
01165 
01166    ast_copy_pj_str(host, remote_stream->conn ? &remote_stream->conn->addr : &remote->conn->addr, sizeof(host));
01167 
01168    /* Ensure that the address provided is valid */
01169    if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
01170       /* The provided host was actually invalid so we error out this negotiation */
01171       return -1;
01172    }
01173 
01174    /* Apply connection information to the RTP instance */
01175    ast_sockaddr_set_port(addrs, remote_stream->desc.port);
01176    ast_rtp_instance_set_remote_address(session_media->rtp, addrs);
01177    if (set_caps(session, session_media, local_stream)) {
01178       return 1;
01179    }
01180 
01181    if ((fdno = media_type_to_fdno(media_type)) < 0) {
01182       return -1;
01183    }
01184    ast_channel_set_fd(session->channel, fdno, ast_rtp_instance_fd(session_media->rtp, 0));
01185    ast_channel_set_fd(session->channel, fdno + 1, ast_rtp_instance_fd(session_media->rtp, 1));
01186 
01187    /* If ICE support is enabled find all the needed attributes */
01188    process_ice_attributes(session, session_media, remote, remote_stream);
01189 
01190    /* Ensure the RTP instance is active */
01191    ast_rtp_instance_activate(session_media->rtp);
01192 
01193    /* audio stream handles music on hold */
01194    if (media_type != AST_MEDIA_TYPE_AUDIO) {
01195       if ((pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_FALSE)
01196          && (session->inv_session->state == PJSIP_INV_STATE_CONFIRMED)) {
01197          ast_queue_control(session->channel, AST_CONTROL_UPDATE_RTP_PEER);
01198       }
01199       return 1;
01200    }
01201 
01202    if (ast_sockaddr_isnull(addrs) ||
01203       ast_sockaddr_is_any(addrs) ||
01204       pjmedia_sdp_media_find_attr2(remote_stream, "sendonly", NULL) ||
01205       pjmedia_sdp_media_find_attr2(remote_stream, "inactive", NULL)) {
01206       if (!session_media->remotely_held) {
01207          /* The remote side has put us on hold */
01208          ast_queue_hold(session->channel, session->endpoint->mohsuggest);
01209          ast_rtp_instance_stop(session_media->rtp);
01210          ast_queue_frame(session->channel, &ast_null_frame);
01211          session_media->remotely_held = 1;
01212       }
01213    } else if (session_media->remotely_held) {
01214       /* The remote side has taken us off hold */
01215       ast_queue_unhold(session->channel);
01216       ast_queue_frame(session->channel, &ast_null_frame);
01217       session_media->remotely_held = 0;
01218    } else if ((pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_FALSE)
01219       && (session->inv_session->state == PJSIP_INV_STATE_CONFIRMED)) {
01220       ast_queue_control(session->channel, AST_CONTROL_UPDATE_RTP_PEER);
01221    }
01222 
01223    /* This purposely resets the encryption to the configured in case it gets added later */
01224    session_media->encryption = session->endpoint->media.rtp.encryption;
01225 
01226    return 1;
01227 }
01228 
01229 /*! \brief Function which updates the media stream with external media address, if applicable */
01230 static void change_outgoing_sdp_stream_media_address(pjsip_tx_data *tdata, struct pjmedia_sdp_media *stream, struct ast_sip_transport *transport)
01231 {
01232    char host[NI_MAXHOST];
01233    struct ast_sockaddr addr = { { 0, } };
01234 
01235    /* If the stream has been rejected there will be no connection line */
01236    if (!stream->conn) {
01237       return;
01238    }
01239 
01240    ast_copy_pj_str(host, &stream->conn->addr, sizeof(host));
01241    ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID);
01242 
01243    /* Is the address within the SDP inside the same network? */
01244    if (ast_apply_ha(transport->localnet, &addr) == AST_SENSE_ALLOW) {
01245       return;
01246    }
01247 
01248    pj_strdup2(tdata->pool, &stream->conn->addr, transport->external_media_address);
01249 }
01250 
01251 /*! \brief Function which destroys the RTP instance when session ends */
01252 static void stream_destroy(struct ast_sip_session_media *session_media)
01253 {
01254    if (session_media->rtp) {
01255       ast_rtp_instance_stop(session_media->rtp);
01256       ast_rtp_instance_destroy(session_media->rtp);
01257    }
01258    session_media->rtp = NULL;
01259 }
01260 
01261 /*! \brief SDP handler for 'audio' media stream */
01262 static struct ast_sip_session_sdp_handler audio_sdp_handler = {
01263    .id = STR_AUDIO,
01264    .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
01265    .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
01266    .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
01267    .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
01268    .stream_destroy = stream_destroy,
01269 };
01270 
01271 /*! \brief SDP handler for 'video' media stream */
01272 static struct ast_sip_session_sdp_handler video_sdp_handler = {
01273    .id = STR_VIDEO,
01274    .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
01275    .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
01276    .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
01277    .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
01278    .stream_destroy = stream_destroy,
01279 };
01280 
01281 static int video_info_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
01282 {
01283    struct pjsip_transaction *tsx;
01284    pjsip_tx_data *tdata;
01285 
01286    if (!session->channel
01287       || !ast_sip_is_content_type(&rdata->msg_info.msg->body->content_type,
01288          "application",
01289          "media_control+xml")) {
01290       return 0;
01291    }
01292 
01293    tsx = pjsip_rdata_get_tsx(rdata);
01294 
01295    ast_queue_control(session->channel, AST_CONTROL_VIDUPDATE);
01296 
01297    if (pjsip_dlg_create_response(session->inv_session->dlg, rdata, 200, NULL, &tdata) == PJ_SUCCESS) {
01298       pjsip_dlg_send_response(session->inv_session->dlg, tsx, tdata);
01299    }
01300 
01301    return 0;
01302 }
01303 
01304 static struct ast_sip_session_supplement video_info_supplement = {
01305    .method = "INFO",
01306    .incoming_request = video_info_incoming_request,
01307 };
01308 
01309 /*! \brief Unloads the sdp RTP/AVP module from Asterisk */
01310 static int unload_module(void)
01311 {
01312    ast_sip_session_unregister_supplement(&video_info_supplement);
01313    ast_sip_session_unregister_sdp_handler(&video_sdp_handler, STR_VIDEO);
01314    ast_sip_session_unregister_sdp_handler(&audio_sdp_handler, STR_AUDIO);
01315 
01316    if (sched) {
01317       ast_sched_context_destroy(sched);
01318    }
01319 
01320    return 0;
01321 }
01322 
01323 /*!
01324  * \brief Load the module
01325  *
01326  * Module loading including tests for configuration or dependencies.
01327  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
01328  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
01329  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
01330  * configuration file or other non-critical problem return
01331  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
01332  */
01333 static int load_module(void)
01334 {
01335    CHECK_PJSIP_SESSION_MODULE_LOADED();
01336 
01337    ast_sockaddr_parse(&address_ipv4, "0.0.0.0", 0);
01338    ast_sockaddr_parse(&address_ipv6, "::", 0);
01339 
01340    if (!(sched = ast_sched_context_create())) {
01341       ast_log(LOG_ERROR, "Unable to create scheduler context.\n");
01342       goto end;
01343    }
01344 
01345    if (ast_sched_start_thread(sched)) {
01346       ast_log(LOG_ERROR, "Unable to create scheduler context thread.\n");
01347       goto end;
01348    }
01349 
01350    if (ast_sip_session_register_sdp_handler(&audio_sdp_handler, STR_AUDIO)) {
01351       ast_log(LOG_ERROR, "Unable to register SDP handler for %s stream type\n", STR_AUDIO);
01352       goto end;
01353    }
01354 
01355    if (ast_sip_session_register_sdp_handler(&video_sdp_handler, STR_VIDEO)) {
01356       ast_log(LOG_ERROR, "Unable to register SDP handler for %s stream type\n", STR_VIDEO);
01357       goto end;
01358    }
01359 
01360    ast_sip_session_register_supplement(&video_info_supplement);
01361 
01362    return AST_MODULE_LOAD_SUCCESS;
01363 end:
01364    unload_module();
01365 
01366    return AST_MODULE_LOAD_FAILURE;
01367 }
01368 
01369 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP SDP RTP/AVP stream handler",
01370       .support_level = AST_MODULE_SUPPORT_CORE,
01371       .load = load_module,
01372       .unload = unload_module,
01373       .load_pri = AST_MODPRI_CHANNEL_DRIVER,
01374    );

Generated on Thu Apr 16 06:27:50 2015 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.6