Merge "rtp_engine/res_rtp_asterisk: Fix RTP struct reentrancy crashes."
[asterisk/asterisk.git] / res / res_pjsip_sdp_rtp.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  * Kevin Harwell <kharwell@digium.com>
8  *
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.
14  *
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.
18  */
19
20 /*! \file
21  *
22  * \author Joshua Colp <jcolp@digium.com>
23  *
24  * \brief SIP SDP media stream handling
25  */
26
27 /*** MODULEINFO
28         <depend>pjproject</depend>
29         <depend>res_pjsip</depend>
30         <depend>res_pjsip_session</depend>
31         <support_level>core</support_level>
32  ***/
33
34 #include "asterisk.h"
35
36 #include <pjsip.h>
37 #include <pjsip_ua.h>
38 #include <pjmedia.h>
39 #include <pjlib.h>
40
41 #include "asterisk/utils.h"
42 #include "asterisk/module.h"
43 #include "asterisk/format.h"
44 #include "asterisk/format_cap.h"
45 #include "asterisk/rtp_engine.h"
46 #include "asterisk/netsock2.h"
47 #include "asterisk/channel.h"
48 #include "asterisk/causes.h"
49 #include "asterisk/sched.h"
50 #include "asterisk/acl.h"
51 #include "asterisk/sdp_srtp.h"
52 #include "asterisk/dsp.h"
53 #include "asterisk/linkedlists.h"       /* for AST_LIST_NEXT */
54
55 #include "asterisk/res_pjsip.h"
56 #include "asterisk/res_pjsip_session.h"
57
58 /*! \brief Scheduler for RTCP purposes */
59 static struct ast_sched_context *sched;
60
61 /*! \brief Address for RTP */
62 static struct ast_sockaddr address_rtp;
63
64 static const char STR_AUDIO[] = "audio";
65 static const int FD_AUDIO = 0;
66
67 static const char STR_VIDEO[] = "video";
68 static const int FD_VIDEO = 2;
69
70 /*! \brief Retrieves an ast_format_type based on the given stream_type */
71 static enum ast_media_type stream_to_media_type(const char *stream_type)
72 {
73         if (!strcasecmp(stream_type, STR_AUDIO)) {
74                 return AST_MEDIA_TYPE_AUDIO;
75         } else if (!strcasecmp(stream_type, STR_VIDEO)) {
76                 return AST_MEDIA_TYPE_VIDEO;
77         }
78
79         return 0;
80 }
81
82 /*! \brief Get the starting descriptor for a media type */
83 static int media_type_to_fdno(enum ast_media_type media_type)
84 {
85         switch (media_type) {
86         case AST_MEDIA_TYPE_AUDIO: return FD_AUDIO;
87         case AST_MEDIA_TYPE_VIDEO: return FD_VIDEO;
88         case AST_MEDIA_TYPE_TEXT:
89         case AST_MEDIA_TYPE_UNKNOWN:
90         case AST_MEDIA_TYPE_IMAGE:
91         case AST_MEDIA_TYPE_END: break;
92         }
93         return -1;
94 }
95
96 /*! \brief Remove all other cap types but the one given */
97 static void format_cap_only_type(struct ast_format_cap *caps, enum ast_media_type media_type)
98 {
99         int i = 0;
100         while (i <= AST_MEDIA_TYPE_TEXT) {
101                 if (i != media_type && i != AST_MEDIA_TYPE_UNKNOWN) {
102                         ast_format_cap_remove_by_type(caps, i);
103                 }
104                 i += 1;
105         }
106 }
107
108 static int send_keepalive(const void *data)
109 {
110         struct ast_sip_session_media *session_media = (struct ast_sip_session_media *) data;
111         struct ast_rtp_instance *rtp = session_media->rtp;
112         int keepalive;
113         time_t interval;
114         int send_keepalive;
115
116         if (!rtp) {
117                 return 0;
118         }
119
120         keepalive = ast_rtp_instance_get_keepalive(rtp);
121
122         if (!ast_sockaddr_isnull(&session_media->direct_media_addr)) {
123                 ast_debug(3, "Not sending RTP keepalive on RTP instance %p since direct media is in use\n", rtp);
124                 return keepalive * 1000;
125         }
126
127         interval = time(NULL) - ast_rtp_instance_get_last_tx(rtp);
128         send_keepalive = interval >= keepalive;
129
130         ast_debug(3, "It has been %d seconds since RTP was last sent on instance %p. %sending keepalive\n",
131                         (int) interval, rtp, send_keepalive ? "S" : "Not s");
132
133         if (send_keepalive) {
134                 ast_rtp_instance_sendcng(rtp, 0);
135                 return keepalive * 1000;
136         }
137
138         return (keepalive - interval) * 1000;
139 }
140
141 /*! \brief Check whether RTP is being received or not */
142 static int rtp_check_timeout(const void *data)
143 {
144         struct ast_sip_session_media *session_media = (struct ast_sip_session_media *)data;
145         struct ast_rtp_instance *rtp = session_media->rtp;
146         int elapsed;
147         struct ast_channel *chan;
148
149         if (!rtp) {
150                 return 0;
151         }
152
153         elapsed = time(NULL) - ast_rtp_instance_get_last_rx(rtp);
154         if (elapsed < ast_rtp_instance_get_timeout(rtp)) {
155                 return (ast_rtp_instance_get_timeout(rtp) - elapsed) * 1000;
156         }
157
158         chan = ast_channel_get_by_name(ast_rtp_instance_get_channel_id(rtp));
159         if (!chan) {
160                 return 0;
161         }
162
163         ast_log(LOG_NOTICE, "Disconnecting channel '%s' for lack of RTP activity in %d seconds\n",
164                 ast_channel_name(chan), elapsed);
165
166         ast_channel_lock(chan);
167         ast_channel_hangupcause_set(chan, AST_CAUSE_REQUESTED_CHAN_UNAVAIL);
168         ast_channel_unlock(chan);
169
170         ast_softhangup(chan, AST_SOFTHANGUP_DEV);
171         ast_channel_unref(chan);
172
173         return 0;
174 }
175
176 /*!
177  * \brief Enable RTCP on an RTP session.
178  */
179 static void enable_rtcp(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
180         const struct pjmedia_sdp_media *remote_media)
181 {
182         enum ast_rtp_instance_rtcp rtcp_type;
183
184         if (session->endpoint->media.rtcp_mux && session_media->remote_rtcp_mux) {
185                 rtcp_type = AST_RTP_INSTANCE_RTCP_MUX;
186         } else {
187                 rtcp_type = AST_RTP_INSTANCE_RTCP_STANDARD;
188         }
189
190         ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_RTCP, rtcp_type);
191 }
192
193 /*! \brief Internal function which creates an RTP instance */
194 static int create_rtp(struct ast_sip_session *session, struct ast_sip_session_media *session_media)
195 {
196         struct ast_rtp_engine_ice *ice;
197         struct ast_sockaddr temp_media_address;
198         struct ast_sockaddr *media_address =  &address_rtp;
199
200         if (session->endpoint->media.bind_rtp_to_media_address && !ast_strlen_zero(session->endpoint->media.address)) {
201                 if (ast_sockaddr_parse(&temp_media_address, session->endpoint->media.address, 0)) {
202                         ast_debug(1, "Endpoint %s: Binding RTP media to %s\n",
203                                 ast_sorcery_object_get_id(session->endpoint),
204                                 session->endpoint->media.address);
205                         media_address = &temp_media_address;
206                 } else {
207                         ast_debug(1, "Endpoint %s: RTP media address invalid: %s\n",
208                                 ast_sorcery_object_get_id(session->endpoint),
209                                 session->endpoint->media.address);
210                 }
211         } else {
212                 struct ast_sip_transport *transport;
213
214                 transport = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "transport",
215                         session->endpoint->transport);
216                 if (transport) {
217                         struct ast_sip_transport_state *trans_state;
218
219                         trans_state = ast_sip_get_transport_state(ast_sorcery_object_get_id(transport));
220                         if (trans_state) {
221                                 char hoststr[PJ_INET6_ADDRSTRLEN];
222
223                                 pj_sockaddr_print(&trans_state->host, hoststr, sizeof(hoststr), 0);
224                                 if (ast_sockaddr_parse(&temp_media_address, hoststr, 0)) {
225                                         ast_debug(1, "Transport %s bound to %s: Using it for RTP media.\n",
226                                                 session->endpoint->transport, hoststr);
227                                         media_address = &temp_media_address;
228                                 } else {
229                                         ast_debug(1, "Transport %s bound to %s: Invalid for RTP media.\n",
230                                                 session->endpoint->transport, hoststr);
231                                 }
232                                 ao2_ref(trans_state, -1);
233                         }
234                         ao2_ref(transport, -1);
235                 }
236         }
237
238         if (!(session_media->rtp = ast_rtp_instance_new(session->endpoint->media.rtp.engine, sched, media_address, NULL))) {
239                 ast_log(LOG_ERROR, "Unable to create RTP instance using RTP engine '%s'\n", session->endpoint->media.rtp.engine);
240                 return -1;
241         }
242
243         ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_NAT, session->endpoint->media.rtp.symmetric);
244
245         if (!session->endpoint->media.rtp.ice_support && (ice = ast_rtp_instance_get_ice(session_media->rtp))) {
246                 ice->stop(session_media->rtp);
247         }
248
249         if (session->endpoint->dtmf == AST_SIP_DTMF_RFC_4733 || session->endpoint->dtmf == AST_SIP_DTMF_AUTO) {
250                 ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_RFC2833);
251                 ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_DTMF, 1);
252         } else if (session->endpoint->dtmf == AST_SIP_DTMF_INBAND) {
253                 ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_INBAND);
254         }
255
256         if (!strcmp(session_media->stream_type, STR_AUDIO) &&
257                         (session->endpoint->media.tos_audio || session->endpoint->media.cos_audio)) {
258                 ast_rtp_instance_set_qos(session_media->rtp, session->endpoint->media.tos_audio,
259                                 session->endpoint->media.cos_audio, "SIP RTP Audio");
260         } else if (!strcmp(session_media->stream_type, STR_VIDEO) &&
261                         (session->endpoint->media.tos_video || session->endpoint->media.cos_video)) {
262                 ast_rtp_instance_set_qos(session_media->rtp, session->endpoint->media.tos_video,
263                                 session->endpoint->media.cos_video, "SIP RTP Video");
264         }
265
266         ast_rtp_instance_set_last_rx(session_media->rtp, time(NULL));
267
268         return 0;
269 }
270
271 static void get_codecs(struct ast_sip_session *session, const struct pjmedia_sdp_media *stream, struct ast_rtp_codecs *codecs,
272        struct ast_sip_session_media *session_media)
273 {
274         pjmedia_sdp_attr *attr;
275         pjmedia_sdp_rtpmap *rtpmap;
276         pjmedia_sdp_fmtp fmtp;
277         struct ast_format *format;
278         int i, num = 0, tel_event = 0;
279         char name[256];
280         char media[20];
281         char fmt_param[256];
282         enum ast_rtp_options options = session->endpoint->media.g726_non_standard ?
283                 AST_RTP_OPT_G726_NONSTANDARD : 0;
284
285         ast_rtp_codecs_payloads_initialize(codecs);
286
287         /* Iterate through provided formats */
288         for (i = 0; i < stream->desc.fmt_count; ++i) {
289                 /* The payload is kept as a string for things like t38 but for video it is always numerical */
290                 ast_rtp_codecs_payloads_set_m_type(codecs, NULL, pj_strtoul(&stream->desc.fmt[i]));
291                 /* Look for the optional rtpmap attribute */
292                 if (!(attr = pjmedia_sdp_media_find_attr2(stream, "rtpmap", &stream->desc.fmt[i]))) {
293                         continue;
294                 }
295
296                 /* Interpret the attribute as an rtpmap */
297                 if ((pjmedia_sdp_attr_to_rtpmap(session->inv_session->pool_prov, attr, &rtpmap)) != PJ_SUCCESS) {
298                         continue;
299                 }
300
301                 ast_copy_pj_str(name, &rtpmap->enc_name, sizeof(name));
302                 if (strcmp(name, "telephone-event") == 0) {
303                         tel_event++;
304                 }
305
306                 ast_copy_pj_str(media, (pj_str_t*)&stream->desc.media, sizeof(media));
307                 ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, NULL,
308                         pj_strtoul(&stream->desc.fmt[i]), media, name, options, rtpmap->clock_rate);
309                 /* Look for an optional associated fmtp attribute */
310                 if (!(attr = pjmedia_sdp_media_find_attr2(stream, "fmtp", &rtpmap->pt))) {
311                         continue;
312                 }
313
314                 if ((pjmedia_sdp_attr_get_fmtp(attr, &fmtp)) == PJ_SUCCESS) {
315                         ast_copy_pj_str(fmt_param, &fmtp.fmt, sizeof(fmt_param));
316                         if (sscanf(fmt_param, "%30d", &num) != 1) {
317                                 continue;
318                         }
319
320                         if ((format = ast_rtp_codecs_get_payload_format(codecs, num))) {
321                                 struct ast_format *format_parsed;
322
323                                 ast_copy_pj_str(fmt_param, &fmtp.fmt_param, sizeof(fmt_param));
324
325                                 format_parsed = ast_format_parse_sdp_fmtp(format, fmt_param);
326                                 if (format_parsed) {
327                                         ast_rtp_codecs_payload_replace_format(codecs, num, format_parsed);
328                                         ao2_ref(format_parsed, -1);
329                                 }
330
331                                 ao2_ref(format, -1);
332                         }
333                 }
334         }
335         if (!tel_event && (session->endpoint->dtmf == AST_SIP_DTMF_AUTO)) {
336                 ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_INBAND);
337         }
338         /* Get the packetization, if it exists */
339         if ((attr = pjmedia_sdp_media_find_attr2(stream, "ptime", NULL))) {
340                 unsigned long framing = pj_strtoul(pj_strltrim(&attr->value));
341                 if (framing && session->endpoint->media.rtp.use_ptime) {
342                         ast_rtp_codecs_set_framing(codecs, framing);
343                 }
344         }
345 }
346
347 static int set_caps(struct ast_sip_session *session,
348         struct ast_sip_session_media *session_media,
349         const struct pjmedia_sdp_media *stream,
350         int is_offer)
351 {
352         RAII_VAR(struct ast_format_cap *, caps, NULL, ao2_cleanup);
353         RAII_VAR(struct ast_format_cap *, peer, NULL, ao2_cleanup);
354         RAII_VAR(struct ast_format_cap *, joint, NULL, ao2_cleanup);
355         enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
356         struct ast_rtp_codecs codecs = AST_RTP_CODECS_NULL_INIT;
357         int fmts = 0;
358         int direct_media_enabled = !ast_sockaddr_isnull(&session_media->direct_media_addr) &&
359                 ast_format_cap_count(session->direct_media_cap);
360         int dsp_features = 0;
361
362         if (!(caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT)) ||
363             !(peer = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT)) ||
364             !(joint = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
365                 ast_log(LOG_ERROR, "Failed to allocate %s capabilities\n", session_media->stream_type);
366                 return -1;
367         }
368
369         /* get the endpoint capabilities */
370         if (direct_media_enabled) {
371                 ast_format_cap_get_compatible(session->endpoint->media.codecs, session->direct_media_cap, caps);
372                 format_cap_only_type(caps, media_type);
373         } else {
374                 ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, media_type);
375         }
376
377         /* get the capabilities on the peer */
378         get_codecs(session, stream, &codecs,  session_media);
379         ast_rtp_codecs_payload_formats(&codecs, peer, &fmts);
380
381         /* get the joint capabilities between peer and endpoint */
382         ast_format_cap_get_compatible(caps, peer, joint);
383         if (!ast_format_cap_count(joint)) {
384                 struct ast_str *usbuf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
385                 struct ast_str *thembuf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
386
387                 ast_rtp_codecs_payloads_destroy(&codecs);
388                 ast_log(LOG_NOTICE, "No joint capabilities for '%s' media stream between our configuration(%s) and incoming SDP(%s)\n",
389                         session_media->stream_type,
390                         ast_format_cap_get_names(caps, &usbuf),
391                         ast_format_cap_get_names(peer, &thembuf));
392                 return -1;
393         }
394
395         if (is_offer) {
396                 /*
397                  * Setup rx payload type mapping to prefer the mapping
398                  * from the peer that the RFC says we SHOULD use.
399                  */
400                 ast_rtp_codecs_payloads_xover(&codecs, &codecs, NULL);
401         }
402         ast_rtp_codecs_payloads_copy(&codecs, ast_rtp_instance_get_codecs(session_media->rtp),
403                 session_media->rtp);
404
405         ast_format_cap_append_from_cap(session->req_caps, joint, AST_MEDIA_TYPE_UNKNOWN);
406
407         if (session->channel) {
408                 ast_channel_lock(session->channel);
409                 ast_format_cap_remove_by_type(caps, AST_MEDIA_TYPE_UNKNOWN);
410                 ast_format_cap_append_from_cap(caps, ast_channel_nativeformats(session->channel),
411                         AST_MEDIA_TYPE_UNKNOWN);
412                 ast_format_cap_remove_by_type(caps, media_type);
413                 if (session->endpoint->preferred_codec_only){
414                         struct ast_format *preferred_fmt = ast_format_cap_get_format(joint, 0);
415                         ast_format_cap_append(caps, preferred_fmt, 0);
416                         ao2_ref(preferred_fmt, -1);
417                 } else {
418                         ast_format_cap_append_from_cap(caps, joint, media_type);
419                 }
420                 /*
421                  * Apply the new formats to the channel, potentially changing
422                  * raw read/write formats and translation path while doing so.
423                  */
424                 ast_channel_nativeformats_set(session->channel, caps);
425                 if (media_type == AST_MEDIA_TYPE_AUDIO) {
426                         ast_set_read_format(session->channel, ast_channel_readformat(session->channel));
427                         ast_set_write_format(session->channel, ast_channel_writeformat(session->channel));
428                 }
429                 if ((session->endpoint->dtmf == AST_SIP_DTMF_AUTO)
430                     && (ast_rtp_instance_dtmf_mode_get(session_media->rtp) == AST_RTP_DTMF_MODE_RFC2833)
431                     && (session->dsp)) {
432                         dsp_features = ast_dsp_get_features(session->dsp);
433                         dsp_features &= ~DSP_FEATURE_DIGIT_DETECT;
434                         if (dsp_features) {
435                                 ast_dsp_set_features(session->dsp, dsp_features);
436                         } else {
437                                 ast_dsp_free(session->dsp);
438                                 session->dsp = NULL;
439                         }
440                 }
441
442                 if (ast_channel_is_bridged(session->channel)) {
443                         ast_channel_set_unbridged_nolock(session->channel, 1);
444                 }
445
446                 ast_channel_unlock(session->channel);
447         }
448
449         ast_rtp_codecs_payloads_destroy(&codecs);
450         return 0;
451 }
452
453 static pjmedia_sdp_attr* generate_rtpmap_attr(struct ast_sip_session *session, pjmedia_sdp_media *media, pj_pool_t *pool,
454                                               int rtp_code, int asterisk_format, struct ast_format *format, int code)
455 {
456         pjmedia_sdp_rtpmap rtpmap;
457         pjmedia_sdp_attr *attr = NULL;
458         char tmp[64];
459         enum ast_rtp_options options = session->endpoint->media.g726_non_standard ?
460                 AST_RTP_OPT_G726_NONSTANDARD : 0;
461
462         snprintf(tmp, sizeof(tmp), "%d", rtp_code);
463         pj_strdup2(pool, &media->desc.fmt[media->desc.fmt_count++], tmp);
464         rtpmap.pt = media->desc.fmt[media->desc.fmt_count - 1];
465         rtpmap.clock_rate = ast_rtp_lookup_sample_rate2(asterisk_format, format, code);
466         pj_strdup2(pool, &rtpmap.enc_name, ast_rtp_lookup_mime_subtype2(asterisk_format, format, code, options));
467         if (!pj_stricmp2(&rtpmap.enc_name, "opus")) {
468                 pj_cstr(&rtpmap.param, "2");
469         } else {
470                 pj_cstr(&rtpmap.param, NULL);
471         }
472
473         pjmedia_sdp_rtpmap_to_attr(pool, &rtpmap, &attr);
474
475         return attr;
476 }
477
478 static pjmedia_sdp_attr* generate_fmtp_attr(pj_pool_t *pool, struct ast_format *format, int rtp_code)
479 {
480         struct ast_str *fmtp0 = ast_str_alloca(256);
481         pj_str_t fmtp1;
482         pjmedia_sdp_attr *attr = NULL;
483         char *tmp;
484
485         ast_format_generate_sdp_fmtp(format, rtp_code, &fmtp0);
486         if (ast_str_strlen(fmtp0)) {
487                 tmp = ast_str_buffer(fmtp0) + ast_str_strlen(fmtp0) - 1;
488                 /* remove any carriage return line feeds */
489                 while (*tmp == '\r' || *tmp == '\n') --tmp;
490                 *++tmp = '\0';
491                 /* ast...generate gives us everything, just need value */
492                 tmp = strchr(ast_str_buffer(fmtp0), ':');
493                 if (tmp && tmp[1] != '\0') {
494                         fmtp1 = pj_str(tmp + 1);
495                 } else {
496                         fmtp1 = pj_str(ast_str_buffer(fmtp0));
497                 }
498                 attr = pjmedia_sdp_attr_create(pool, "fmtp", &fmtp1);
499         }
500         return attr;
501 }
502
503 /*! \brief Function which adds ICE attributes to a media stream */
504 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)
505 {
506         struct ast_rtp_engine_ice *ice;
507         struct ao2_container *candidates;
508         const char *username, *password;
509         pj_str_t stmp;
510         pjmedia_sdp_attr *attr;
511         struct ao2_iterator it_candidates;
512         struct ast_rtp_engine_ice_candidate *candidate;
513
514         if (!session->endpoint->media.rtp.ice_support || !(ice = ast_rtp_instance_get_ice(session_media->rtp)) ||
515                 !(candidates = ice->get_local_candidates(session_media->rtp))) {
516                 return;
517         }
518
519         if ((username = ice->get_ufrag(session_media->rtp))) {
520                 attr = pjmedia_sdp_attr_create(pool, "ice-ufrag", pj_cstr(&stmp, username));
521                 media->attr[media->attr_count++] = attr;
522         }
523
524         if ((password = ice->get_password(session_media->rtp))) {
525                 attr = pjmedia_sdp_attr_create(pool, "ice-pwd", pj_cstr(&stmp, password));
526                 media->attr[media->attr_count++] = attr;
527         }
528
529         it_candidates = ao2_iterator_init(candidates, 0);
530         for (; (candidate = ao2_iterator_next(&it_candidates)); ao2_ref(candidate, -1)) {
531                 struct ast_str *attr_candidate = ast_str_create(128);
532
533                 ast_str_set(&attr_candidate, -1, "%s %u %s %d %s ", candidate->foundation, candidate->id, candidate->transport,
534                                         candidate->priority, ast_sockaddr_stringify_addr_remote(&candidate->address));
535                 ast_str_append(&attr_candidate, -1, "%s typ ", ast_sockaddr_stringify_port(&candidate->address));
536
537                 switch (candidate->type) {
538                         case AST_RTP_ICE_CANDIDATE_TYPE_HOST:
539                                 ast_str_append(&attr_candidate, -1, "host");
540                                 break;
541                         case AST_RTP_ICE_CANDIDATE_TYPE_SRFLX:
542                                 ast_str_append(&attr_candidate, -1, "srflx");
543                                 break;
544                         case AST_RTP_ICE_CANDIDATE_TYPE_RELAYED:
545                                 ast_str_append(&attr_candidate, -1, "relay");
546                                 break;
547                 }
548
549                 if (!ast_sockaddr_isnull(&candidate->relay_address)) {
550                         ast_str_append(&attr_candidate, -1, " raddr %s rport", ast_sockaddr_stringify_addr_remote(&candidate->relay_address));
551                         ast_str_append(&attr_candidate, -1, " %s", ast_sockaddr_stringify_port(&candidate->relay_address));
552                 }
553
554                 attr = pjmedia_sdp_attr_create(pool, "candidate", pj_cstr(&stmp, ast_str_buffer(attr_candidate)));
555                 media->attr[media->attr_count++] = attr;
556
557                 ast_free(attr_candidate);
558         }
559
560         ao2_iterator_destroy(&it_candidates);
561         ao2_ref(candidates, -1);
562 }
563
564 /*! \brief Function which processes ICE attributes in an audio stream */
565 static void process_ice_attributes(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
566                                    const struct pjmedia_sdp_session *remote, const struct pjmedia_sdp_media *remote_stream)
567 {
568         struct ast_rtp_engine_ice *ice;
569         const pjmedia_sdp_attr *attr;
570         char attr_value[256];
571         unsigned int attr_i;
572
573         /* If ICE support is not enabled or available exit early */
574         if (!session->endpoint->media.rtp.ice_support || !(ice = ast_rtp_instance_get_ice(session_media->rtp))) {
575                 return;
576         }
577
578         attr = pjmedia_sdp_media_find_attr2(remote_stream, "ice-ufrag", NULL);
579         if (!attr) {
580                 attr = pjmedia_sdp_attr_find2(remote->attr_count, remote->attr, "ice-ufrag", NULL);
581         }
582         if (attr) {
583                 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
584                 ice->set_authentication(session_media->rtp, attr_value, NULL);
585         } else {
586                 return;
587         }
588
589         attr = pjmedia_sdp_media_find_attr2(remote_stream, "ice-pwd", NULL);
590         if (!attr) {
591                 attr = pjmedia_sdp_attr_find2(remote->attr_count, remote->attr, "ice-pwd", NULL);
592         }
593         if (attr) {
594                 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
595                 ice->set_authentication(session_media->rtp, NULL, attr_value);
596         } else {
597                 return;
598         }
599
600         if (pjmedia_sdp_media_find_attr2(remote_stream, "ice-lite", NULL)) {
601                 ice->ice_lite(session_media->rtp);
602         }
603
604         /* Find all of the candidates */
605         for (attr_i = 0; attr_i < remote_stream->attr_count; ++attr_i) {
606                 char foundation[32], transport[32], address[PJ_INET6_ADDRSTRLEN + 1], cand_type[6], relay_address[PJ_INET6_ADDRSTRLEN + 1] = "";
607                 unsigned int port, relay_port = 0;
608                 struct ast_rtp_engine_ice_candidate candidate = { 0, };
609
610                 attr = remote_stream->attr[attr_i];
611
612                 /* If this is not a candidate line skip it */
613                 if (pj_strcmp2(&attr->name, "candidate")) {
614                         continue;
615                 }
616
617                 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
618
619                 if (sscanf(attr_value, "%31s %30u %31s %30u %46s %30u typ %5s %*s %23s %*s %30u", foundation, &candidate.id, transport,
620                         (unsigned *)&candidate.priority, address, &port, cand_type, relay_address, &relay_port) < 7) {
621                         /* Candidate did not parse properly */
622                         continue;
623                 }
624
625                 if (session->endpoint->media.rtcp_mux && session_media->remote_rtcp_mux && candidate.id > 1) {
626                         /* Remote side may have offered RTP and RTCP candidates. However, if we're using RTCP MUX,
627                          * then we should ignore RTCP candidates.
628                          */
629                         continue;
630                 }
631
632                 candidate.foundation = foundation;
633                 candidate.transport = transport;
634
635                 ast_sockaddr_parse(&candidate.address, address, PARSE_PORT_FORBID);
636                 ast_sockaddr_set_port(&candidate.address, port);
637
638                 if (!strcasecmp(cand_type, "host")) {
639                         candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
640                 } else if (!strcasecmp(cand_type, "srflx")) {
641                         candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
642                 } else if (!strcasecmp(cand_type, "relay")) {
643                         candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
644                 } else {
645                         continue;
646                 }
647
648                 if (!ast_strlen_zero(relay_address)) {
649                         ast_sockaddr_parse(&candidate.relay_address, relay_address, PARSE_PORT_FORBID);
650                 }
651
652                 if (relay_port) {
653                         ast_sockaddr_set_port(&candidate.relay_address, relay_port);
654                 }
655
656                 ice->add_remote_candidate(session_media->rtp, &candidate);
657         }
658
659         ice->set_role(session_media->rtp, pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_TRUE ?
660                 AST_RTP_ICE_ROLE_CONTROLLING : AST_RTP_ICE_ROLE_CONTROLLED);
661         ice->start(session_media->rtp);
662 }
663
664 /*! \brief figure out if media stream has crypto lines for sdes */
665 static int media_stream_has_crypto(const struct pjmedia_sdp_media *stream)
666 {
667         int i;
668
669         for (i = 0; i < stream->attr_count; i++) {
670                 pjmedia_sdp_attr *attr;
671
672                 /* check the stream for the required crypto attribute */
673                 attr = stream->attr[i];
674                 if (pj_strcmp2(&attr->name, "crypto")) {
675                         continue;
676                 }
677
678                 return 1;
679         }
680
681         return 0;
682 }
683
684 /*! \brief figure out media transport encryption type from the media transport string */
685 static enum ast_sip_session_media_encryption get_media_encryption_type(pj_str_t transport,
686         const struct pjmedia_sdp_media *stream, unsigned int *optimistic)
687 {
688         RAII_VAR(char *, transport_str, ast_strndup(transport.ptr, transport.slen), ast_free);
689
690         *optimistic = 0;
691
692         if (!transport_str) {
693                 return AST_SIP_MEDIA_TRANSPORT_INVALID;
694         }
695         if (strstr(transport_str, "UDP/TLS")) {
696                 return AST_SIP_MEDIA_ENCRYPT_DTLS;
697         } else if (strstr(transport_str, "SAVP")) {
698                 return AST_SIP_MEDIA_ENCRYPT_SDES;
699         } else if (media_stream_has_crypto(stream)) {
700                 *optimistic = 1;
701                 return AST_SIP_MEDIA_ENCRYPT_SDES;
702         } else {
703                 return AST_SIP_MEDIA_ENCRYPT_NONE;
704         }
705 }
706
707 /*!
708  * \brief Checks whether the encryption offered in SDP is compatible with the endpoint's configuration
709  * \internal
710  *
711  * \param endpoint_encryption Media encryption configured for the endpoint
712  * \param stream pjmedia_sdp_media stream description
713  *
714  * \retval AST_SIP_MEDIA_TRANSPORT_INVALID on encryption mismatch
715  * \retval The encryption requested in the SDP
716  */
717 static enum ast_sip_session_media_encryption check_endpoint_media_transport(
718         struct ast_sip_endpoint *endpoint,
719         const struct pjmedia_sdp_media *stream)
720 {
721         enum ast_sip_session_media_encryption incoming_encryption;
722         char transport_end = stream->desc.transport.ptr[stream->desc.transport.slen - 1];
723         unsigned int optimistic;
724
725         if ((transport_end == 'F' && !endpoint->media.rtp.use_avpf)
726                 || (transport_end != 'F' && endpoint->media.rtp.use_avpf)) {
727                 return AST_SIP_MEDIA_TRANSPORT_INVALID;
728         }
729
730         incoming_encryption = get_media_encryption_type(stream->desc.transport, stream, &optimistic);
731
732         if (incoming_encryption == endpoint->media.rtp.encryption) {
733                 return incoming_encryption;
734         }
735
736         if (endpoint->media.rtp.force_avp ||
737                 endpoint->media.rtp.encryption_optimistic) {
738                 return incoming_encryption;
739         }
740
741         /* If an optimistic offer has been made but encryption is not enabled consider it as having
742          * no offer of crypto at all instead of invalid so the session proceeds.
743          */
744         if (optimistic) {
745                 return AST_SIP_MEDIA_ENCRYPT_NONE;
746         }
747
748         return AST_SIP_MEDIA_TRANSPORT_INVALID;
749 }
750
751 static int setup_srtp(struct ast_sip_session_media *session_media)
752 {
753         if (!session_media->srtp) {
754                 session_media->srtp = ast_sdp_srtp_alloc();
755                 if (!session_media->srtp) {
756                         return -1;
757                 }
758         }
759
760         if (!session_media->srtp->crypto) {
761                 session_media->srtp->crypto = ast_sdp_crypto_alloc();
762                 if (!session_media->srtp->crypto) {
763                         return -1;
764                 }
765         }
766
767         return 0;
768 }
769
770 static int setup_dtls_srtp(struct ast_sip_session *session,
771         struct ast_sip_session_media *session_media)
772 {
773         struct ast_rtp_engine_dtls *dtls;
774
775         if (!session->endpoint->media.rtp.dtls_cfg.enabled || !session_media->rtp) {
776                 return -1;
777         }
778
779         dtls = ast_rtp_instance_get_dtls(session_media->rtp);
780         if (!dtls) {
781                 return -1;
782         }
783
784         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);
785         if (dtls->set_configuration(session_media->rtp, &session->endpoint->media.rtp.dtls_cfg)) {
786                 ast_log(LOG_ERROR, "Attempted to set an invalid DTLS-SRTP configuration on RTP instance '%p'\n",
787                         session_media->rtp);
788                 return -1;
789         }
790
791         if (setup_srtp(session_media)) {
792                 return -1;
793         }
794         return 0;
795 }
796
797 static void apply_dtls_attrib(struct ast_sip_session_media *session_media,
798         pjmedia_sdp_attr *attr)
799 {
800         struct ast_rtp_engine_dtls *dtls = ast_rtp_instance_get_dtls(session_media->rtp);
801         pj_str_t *value;
802
803         if (!attr->value.ptr || !dtls) {
804                 return;
805         }
806
807         value = pj_strtrim(&attr->value);
808
809         if (!pj_strcmp2(&attr->name, "setup")) {
810                 if (!pj_stricmp2(value, "active")) {
811                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_ACTIVE);
812                 } else if (!pj_stricmp2(value, "passive")) {
813                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_PASSIVE);
814                 } else if (!pj_stricmp2(value, "actpass")) {
815                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_ACTPASS);
816                 } else if (!pj_stricmp2(value, "holdconn")) {
817                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_HOLDCONN);
818                 } else {
819                         ast_log(LOG_WARNING, "Unsupported setup attribute value '%*s'\n", (int)value->slen, value->ptr);
820                 }
821         } else if (!pj_strcmp2(&attr->name, "connection")) {
822                 if (!pj_stricmp2(value, "new")) {
823                         dtls->reset(session_media->rtp);
824                 } else if (!pj_stricmp2(value, "existing")) {
825                         /* Do nothing */
826                 } else {
827                         ast_log(LOG_WARNING, "Unsupported connection attribute value '%*s'\n", (int)value->slen, value->ptr);
828                 }
829         } else if (!pj_strcmp2(&attr->name, "fingerprint")) {
830                 char hash_value[256], hash[32];
831                 char fingerprint_text[value->slen + 1];
832                 ast_copy_pj_str(fingerprint_text, value, sizeof(fingerprint_text));
833                         if (sscanf(fingerprint_text, "%31s %255s", hash, hash_value) == 2) {
834                         if (!strcasecmp(hash, "sha-1")) {
835                                 dtls->set_fingerprint(session_media->rtp, AST_RTP_DTLS_HASH_SHA1, hash_value);
836                         } else if (!strcasecmp(hash, "sha-256")) {
837                                 dtls->set_fingerprint(session_media->rtp, AST_RTP_DTLS_HASH_SHA256, hash_value);
838                         } else {
839                                 ast_log(LOG_WARNING, "Unsupported fingerprint hash type '%s'\n",
840                                 hash);
841                         }
842                 }
843         }
844 }
845
846 static int parse_dtls_attrib(struct ast_sip_session_media *session_media,
847         const struct pjmedia_sdp_session *sdp,
848         const struct pjmedia_sdp_media *stream)
849 {
850         int i;
851
852         for (i = 0; i < sdp->attr_count; i++) {
853                 apply_dtls_attrib(session_media, sdp->attr[i]);
854         }
855
856         for (i = 0; i < stream->attr_count; i++) {
857                 apply_dtls_attrib(session_media, stream->attr[i]);
858         }
859
860         ast_set_flag(session_media->srtp, AST_SRTP_CRYPTO_OFFER_OK);
861
862         return 0;
863 }
864
865 static int setup_sdes_srtp(struct ast_sip_session_media *session_media,
866         const struct pjmedia_sdp_media *stream)
867 {
868         int i;
869
870         for (i = 0; i < stream->attr_count; i++) {
871                 pjmedia_sdp_attr *attr;
872                 RAII_VAR(char *, crypto_str, NULL, ast_free);
873
874                 /* check the stream for the required crypto attribute */
875                 attr = stream->attr[i];
876                 if (pj_strcmp2(&attr->name, "crypto")) {
877                         continue;
878                 }
879
880                 crypto_str = ast_strndup(attr->value.ptr, attr->value.slen);
881                 if (!crypto_str) {
882                         return -1;
883                 }
884
885                 if (setup_srtp(session_media)) {
886                         return -1;
887                 }
888
889                 if (!ast_sdp_crypto_process(session_media->rtp, session_media->srtp, crypto_str)) {
890                         /* found a valid crypto attribute */
891                         return 0;
892                 }
893
894                 ast_debug(1, "Ignoring crypto offer with unsupported parameters: %s\n", crypto_str);
895         }
896
897         /* no usable crypto attributes found */
898         return -1;
899 }
900
901 static int setup_media_encryption(struct ast_sip_session *session,
902         struct ast_sip_session_media *session_media,
903         const struct pjmedia_sdp_session *sdp,
904         const struct pjmedia_sdp_media *stream)
905 {
906         switch (session_media->encryption) {
907         case AST_SIP_MEDIA_ENCRYPT_SDES:
908                 if (setup_sdes_srtp(session_media, stream)) {
909                         return -1;
910                 }
911                 break;
912         case AST_SIP_MEDIA_ENCRYPT_DTLS:
913                 if (setup_dtls_srtp(session, session_media)) {
914                         return -1;
915                 }
916                 if (parse_dtls_attrib(session_media, sdp, stream)) {
917                         return -1;
918                 }
919                 break;
920         case AST_SIP_MEDIA_TRANSPORT_INVALID:
921         case AST_SIP_MEDIA_ENCRYPT_NONE:
922                 break;
923         }
924
925         return 0;
926 }
927
928 static void set_ice_components(struct ast_sip_session *session, struct ast_sip_session_media *session_media)
929 {
930         struct ast_rtp_engine_ice *ice;
931
932         ast_assert(session_media->rtp != NULL);
933
934         ice = ast_rtp_instance_get_ice(session_media->rtp);
935         if (!session->endpoint->media.rtp.ice_support || !ice) {
936                 return;
937         }
938
939         if (session->endpoint->media.rtcp_mux && session_media->remote_rtcp_mux) {
940                 /* We both support RTCP mux. Only one ICE component necessary */
941                 ice->change_components(session_media->rtp, 1);
942         } else {
943                 /* They either don't support RTCP mux or we don't know if they do yet. */
944                 ice->change_components(session_media->rtp, 2);
945         }
946 }
947
948 /*! \brief Function which negotiates an incoming media stream */
949 static int negotiate_incoming_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
950                                          const struct pjmedia_sdp_session *sdp, const struct pjmedia_sdp_media *stream)
951 {
952         char host[NI_MAXHOST];
953         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
954         enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
955         enum ast_sip_session_media_encryption encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
956         int res;
957
958         /* If port is 0, ignore this media stream */
959         if (!stream->desc.port) {
960                 ast_debug(3, "Media stream '%s' is already declined\n", session_media->stream_type);
961                 return 0;
962         }
963
964         /* If no type formats have been configured reject this stream */
965         if (!ast_format_cap_has_type(session->endpoint->media.codecs, media_type)) {
966                 ast_debug(3, "Endpoint has no codecs for media type '%s', declining stream\n", session_media->stream_type);
967                 return 0;
968         }
969
970         /* Ensure incoming transport is compatible with the endpoint's configuration */
971         if (!session->endpoint->media.rtp.use_received_transport) {
972                 encryption = check_endpoint_media_transport(session->endpoint, stream);
973
974                 if (encryption == AST_SIP_MEDIA_TRANSPORT_INVALID) {
975                         return -1;
976                 }
977         }
978
979         ast_copy_pj_str(host, stream->conn ? &stream->conn->addr : &sdp->conn->addr, sizeof(host));
980
981         /* Ensure that the address provided is valid */
982         if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
983                 /* The provided host was actually invalid so we error out this negotiation */
984                 return -1;
985         }
986
987         /* Using the connection information create an appropriate RTP instance */
988         if (!session_media->rtp && create_rtp(session, session_media)) {
989                 return -1;
990         }
991
992         session_media->remote_rtcp_mux = (pjmedia_sdp_media_find_attr2(stream, "rtcp-mux", NULL) != NULL);
993         set_ice_components(session, session_media);
994
995         enable_rtcp(session, session_media, stream);
996
997         res = setup_media_encryption(session, session_media, sdp, stream);
998         if (res) {
999                 if (!session->endpoint->media.rtp.encryption_optimistic ||
1000                         !pj_strncmp2(&stream->desc.transport, "RTP/SAVP", 8)) {
1001                         /* If optimistic encryption is disabled and crypto should have been enabled
1002                          * but was not this session must fail. This must also fail if crypto was
1003                          * required in the offer but could not be set up.
1004                          */
1005                         return -1;
1006                 }
1007                 /* There is no encryption, sad. */
1008                 session_media->encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
1009         }
1010
1011         /* If we've been explicitly configured to use the received transport OR if
1012          * encryption is on and crypto is present use the received transport.
1013          * This is done in case of optimistic because it may come in as RTP/AVP or RTP/SAVP depending
1014          * on the configuration of the remote endpoint (optimistic themselves or mandatory).
1015          */
1016         if ((session->endpoint->media.rtp.use_received_transport) ||
1017                 ((encryption == AST_SIP_MEDIA_ENCRYPT_SDES) && !res)) {
1018                 pj_strdup(session->inv_session->pool, &session_media->transport, &stream->desc.transport);
1019         }
1020
1021         if (set_caps(session, session_media, stream, 1)) {
1022                 return 0;
1023         }
1024         return 1;
1025 }
1026
1027 static int add_crypto_to_stream(struct ast_sip_session *session,
1028         struct ast_sip_session_media *session_media,
1029         pj_pool_t *pool, pjmedia_sdp_media *media)
1030 {
1031         pj_str_t stmp;
1032         pjmedia_sdp_attr *attr;
1033         enum ast_rtp_dtls_hash hash;
1034         const char *crypto_attribute;
1035         struct ast_rtp_engine_dtls *dtls;
1036         struct ast_sdp_srtp *tmp;
1037         static const pj_str_t STR_NEW = { "new", 3 };
1038         static const pj_str_t STR_EXISTING = { "existing", 8 };
1039         static const pj_str_t STR_ACTIVE = { "active", 6 };
1040         static const pj_str_t STR_PASSIVE = { "passive", 7 };
1041         static const pj_str_t STR_ACTPASS = { "actpass", 7 };
1042         static const pj_str_t STR_HOLDCONN = { "holdconn", 8 };
1043
1044         switch (session_media->encryption) {
1045         case AST_SIP_MEDIA_ENCRYPT_NONE:
1046         case AST_SIP_MEDIA_TRANSPORT_INVALID:
1047                 break;
1048         case AST_SIP_MEDIA_ENCRYPT_SDES:
1049                 if (!session_media->srtp) {
1050                         session_media->srtp = ast_sdp_srtp_alloc();
1051                         if (!session_media->srtp) {
1052                                 return -1;
1053                         }
1054                 }
1055
1056                 tmp = session_media->srtp;
1057
1058                 do {
1059                         crypto_attribute = ast_sdp_srtp_get_attrib(tmp,
1060                                 0 /* DTLS running? No */,
1061                                 session->endpoint->media.rtp.srtp_tag_32 /* 32 byte tag length? */);
1062                         if (!crypto_attribute) {
1063                                 /* No crypto attribute to add, bad news */
1064                                 return -1;
1065                         }
1066
1067                         attr = pjmedia_sdp_attr_create(pool, "crypto",
1068                                 pj_cstr(&stmp, crypto_attribute));
1069                         media->attr[media->attr_count++] = attr;
1070                 } while ((tmp = AST_LIST_NEXT(tmp, sdp_srtp_list)));
1071
1072                 break;
1073         case AST_SIP_MEDIA_ENCRYPT_DTLS:
1074                 if (setup_dtls_srtp(session, session_media)) {
1075                         return -1;
1076                 }
1077
1078                 dtls = ast_rtp_instance_get_dtls(session_media->rtp);
1079                 if (!dtls) {
1080                         return -1;
1081                 }
1082
1083                 switch (dtls->get_connection(session_media->rtp)) {
1084                 case AST_RTP_DTLS_CONNECTION_NEW:
1085                         attr = pjmedia_sdp_attr_create(pool, "connection", &STR_NEW);
1086                         media->attr[media->attr_count++] = attr;
1087                         break;
1088                 case AST_RTP_DTLS_CONNECTION_EXISTING:
1089                         attr = pjmedia_sdp_attr_create(pool, "connection", &STR_EXISTING);
1090                         media->attr[media->attr_count++] = attr;
1091                         break;
1092                 default:
1093                         break;
1094                 }
1095
1096                 switch (dtls->get_setup(session_media->rtp)) {
1097                 case AST_RTP_DTLS_SETUP_ACTIVE:
1098                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_ACTIVE);
1099                         media->attr[media->attr_count++] = attr;
1100                         break;
1101                 case AST_RTP_DTLS_SETUP_PASSIVE:
1102                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_PASSIVE);
1103                         media->attr[media->attr_count++] = attr;
1104                         break;
1105                 case AST_RTP_DTLS_SETUP_ACTPASS:
1106                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_ACTPASS);
1107                         media->attr[media->attr_count++] = attr;
1108                         break;
1109                 case AST_RTP_DTLS_SETUP_HOLDCONN:
1110                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_HOLDCONN);
1111                         media->attr[media->attr_count++] = attr;
1112                         break;
1113                 default:
1114                         break;
1115                 }
1116
1117                 hash = dtls->get_fingerprint_hash(session_media->rtp);
1118                 crypto_attribute = dtls->get_fingerprint(session_media->rtp);
1119                 if (crypto_attribute && (hash == AST_RTP_DTLS_HASH_SHA1 || hash == AST_RTP_DTLS_HASH_SHA256)) {
1120                         RAII_VAR(struct ast_str *, fingerprint, ast_str_create(64), ast_free);
1121                         if (!fingerprint) {
1122                                 return -1;
1123                         }
1124
1125                         if (hash == AST_RTP_DTLS_HASH_SHA1) {
1126                                 ast_str_set(&fingerprint, 0, "SHA-1 %s", crypto_attribute);
1127                         } else {
1128                                 ast_str_set(&fingerprint, 0, "SHA-256 %s", crypto_attribute);
1129                         }
1130
1131                         attr = pjmedia_sdp_attr_create(pool, "fingerprint", pj_cstr(&stmp, ast_str_buffer(fingerprint)));
1132                         media->attr[media->attr_count++] = attr;
1133                 }
1134                 break;
1135         }
1136
1137         return 0;
1138 }
1139
1140 /*! \brief Function which creates an outgoing stream */
1141 static int create_outgoing_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
1142                                       struct pjmedia_sdp_session *sdp)
1143 {
1144         pj_pool_t *pool = session->inv_session->pool_prov;
1145         static const pj_str_t STR_IN = { "IN", 2 };
1146         static const pj_str_t STR_IP4 = { "IP4", 3};
1147         static const pj_str_t STR_IP6 = { "IP6", 3};
1148         static const pj_str_t STR_SENDRECV = { "sendrecv", 8 };
1149         static const pj_str_t STR_SENDONLY = { "sendonly", 8 };
1150         pjmedia_sdp_media *media;
1151         const char *hostip = NULL;
1152         struct ast_sockaddr addr;
1153         char tmp[512];
1154         pj_str_t stmp;
1155         pjmedia_sdp_attr *attr;
1156         int index = 0;
1157         int noncodec = (session->endpoint->dtmf == AST_SIP_DTMF_RFC_4733 || session->endpoint->dtmf == AST_SIP_DTMF_AUTO) ? AST_RTP_DTMF : 0;
1158         int min_packet_size = 0, max_packet_size = 0;
1159         int rtp_code;
1160         RAII_VAR(struct ast_format_cap *, caps, NULL, ao2_cleanup);
1161         enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
1162         int use_override_prefs = ast_format_cap_count(session->req_caps);
1163
1164         int direct_media_enabled = !ast_sockaddr_isnull(&session_media->direct_media_addr) &&
1165                 ast_format_cap_count(session->direct_media_cap);
1166
1167         if ((use_override_prefs && !ast_format_cap_has_type(session->req_caps, media_type)) ||
1168             (!use_override_prefs && !ast_format_cap_has_type(session->endpoint->media.codecs, media_type))) {
1169                 /* If no type formats are configured don't add a stream */
1170                 return 0;
1171         } else if (!session_media->rtp && create_rtp(session, session_media)) {
1172                 return -1;
1173         }
1174
1175         set_ice_components(session, session_media);
1176         enable_rtcp(session, session_media, NULL);
1177
1178         if (!(media = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_media))) ||
1179                 !(media->conn = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_conn)))) {
1180                 return -1;
1181         }
1182
1183         if (add_crypto_to_stream(session, session_media, pool, media)) {
1184                 return -1;
1185         }
1186
1187         media->desc.media = pj_str(session_media->stream_type);
1188         if (pj_strlen(&session_media->transport)) {
1189                 /* If a transport has already been specified use it */
1190                 media->desc.transport = session_media->transport;
1191         } else {
1192                 media->desc.transport = pj_str(ast_sdp_get_rtp_profile(
1193                         /* Optimistic encryption places crypto in the normal RTP/AVP profile */
1194                         !session->endpoint->media.rtp.encryption_optimistic &&
1195                                 (session_media->encryption == AST_SIP_MEDIA_ENCRYPT_SDES),
1196                         session_media->rtp, session->endpoint->media.rtp.use_avpf,
1197                         session->endpoint->media.rtp.force_avp));
1198         }
1199
1200         /* Add connection level details */
1201         if (direct_media_enabled) {
1202                 hostip = ast_sockaddr_stringify_fmt(&session_media->direct_media_addr, AST_SOCKADDR_STR_ADDR);
1203         } else if (ast_strlen_zero(session->endpoint->media.address)) {
1204                 hostip = ast_sip_get_host_ip_string(session->endpoint->media.rtp.ipv6 ? pj_AF_INET6() : pj_AF_INET());
1205         } else {
1206                 hostip = session->endpoint->media.address;
1207         }
1208
1209         if (ast_strlen_zero(hostip)) {
1210                 ast_log(LOG_ERROR, "No local host IP available for stream %s\n", session_media->stream_type);
1211                 return -1;
1212         }
1213
1214         media->conn->net_type = STR_IN;
1215         /* Assume that the connection will use IPv4 until proven otherwise */
1216         media->conn->addr_type = STR_IP4;
1217         pj_strdup2(pool, &media->conn->addr, hostip);
1218
1219         if (!ast_strlen_zero(session->endpoint->media.address)) {
1220                 pj_sockaddr ip;
1221
1222                 if ((pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &media->conn->addr, &ip) == PJ_SUCCESS) &&
1223                         (ip.addr.sa_family == pj_AF_INET6())) {
1224                         media->conn->addr_type = STR_IP6;
1225                 }
1226         }
1227
1228         ast_rtp_instance_get_local_address(session_media->rtp, &addr);
1229         media->desc.port = direct_media_enabled ? ast_sockaddr_port(&session_media->direct_media_addr) : (pj_uint16_t) ast_sockaddr_port(&addr);
1230         media->desc.port_count = 1;
1231
1232         /* Add ICE attributes and candidates */
1233         add_ice_to_stream(session, session_media, pool, media);
1234
1235         if (!(caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1236                 ast_log(LOG_ERROR, "Failed to allocate %s capabilities\n", session_media->stream_type);
1237                 return -1;
1238         }
1239
1240         if (direct_media_enabled) {
1241                 ast_format_cap_get_compatible(session->endpoint->media.codecs, session->direct_media_cap, caps);
1242         } else if (!ast_format_cap_count(session->req_caps) ||
1243                 !ast_format_cap_iscompatible(session->req_caps, session->endpoint->media.codecs)) {
1244                 ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, media_type);
1245         } else {
1246                 ast_format_cap_append_from_cap(caps, session->req_caps, media_type);
1247         }
1248
1249         for (index = 0; index < ast_format_cap_count(caps); ++index) {
1250                 struct ast_format *format = ast_format_cap_get_format(caps, index);
1251
1252                 if (ast_format_get_type(format) != media_type) {
1253                         ao2_ref(format, -1);
1254                         continue;
1255                 }
1256
1257                 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(session_media->rtp), 1, format, 0)) == -1) {
1258                         ast_log(LOG_WARNING,"Unable to get rtp codec payload code for %s\n", ast_format_get_name(format));
1259                         ao2_ref(format, -1);
1260                         continue;
1261                 }
1262
1263                 if (!(attr = generate_rtpmap_attr(session, media, pool, rtp_code, 1, format, 0))) {
1264                         ao2_ref(format, -1);
1265                         continue;
1266                 }
1267                 media->attr[media->attr_count++] = attr;
1268
1269                 if ((attr = generate_fmtp_attr(pool, format, rtp_code))) {
1270                         media->attr[media->attr_count++] = attr;
1271                 }
1272
1273                 if (ast_format_get_maximum_ms(format) &&
1274                         ((ast_format_get_maximum_ms(format) < max_packet_size) || !max_packet_size)) {
1275                         max_packet_size = ast_format_get_maximum_ms(format);
1276                 }
1277                 ao2_ref(format, -1);
1278
1279                 if (media->desc.fmt_count == PJMEDIA_MAX_SDP_FMT) {
1280                         break;
1281                 }
1282         }
1283
1284         /* Add non-codec formats */
1285         if (media_type != AST_MEDIA_TYPE_VIDEO && media->desc.fmt_count < PJMEDIA_MAX_SDP_FMT) {
1286                 for (index = 1LL; index <= AST_RTP_MAX; index <<= 1) {
1287                         if (!(noncodec & index)) {
1288                                 continue;
1289                         }
1290                         rtp_code = ast_rtp_codecs_payload_code(
1291                                 ast_rtp_instance_get_codecs(session_media->rtp), 0, NULL, index);
1292                         if (rtp_code == -1) {
1293                                 continue;
1294                         }
1295
1296                         if (!(attr = generate_rtpmap_attr(session, media, pool, rtp_code, 0, NULL, index))) {
1297                                 continue;
1298                         }
1299
1300                         media->attr[media->attr_count++] = attr;
1301
1302                         if (index == AST_RTP_DTMF) {
1303                                 snprintf(tmp, sizeof(tmp), "%d 0-16", rtp_code);
1304                                 attr = pjmedia_sdp_attr_create(pool, "fmtp", pj_cstr(&stmp, tmp));
1305                                 media->attr[media->attr_count++] = attr;
1306                         }
1307
1308                         if (media->desc.fmt_count == PJMEDIA_MAX_SDP_FMT) {
1309                                 break;
1310                         }
1311                 }
1312         }
1313
1314         /* If no formats were actually added to the media stream don't add it to the SDP */
1315         if (!media->desc.fmt_count) {
1316                 return 1;
1317         }
1318
1319         /* If ptime is set add it as an attribute */
1320         min_packet_size = ast_rtp_codecs_get_framing(ast_rtp_instance_get_codecs(session_media->rtp));
1321         if (!min_packet_size) {
1322                 min_packet_size = ast_format_cap_get_framing(caps);
1323         }
1324         if (min_packet_size) {
1325                 snprintf(tmp, sizeof(tmp), "%d", min_packet_size);
1326                 attr = pjmedia_sdp_attr_create(pool, "ptime", pj_cstr(&stmp, tmp));
1327                 media->attr[media->attr_count++] = attr;
1328         }
1329
1330         if (max_packet_size) {
1331                 snprintf(tmp, sizeof(tmp), "%d", max_packet_size);
1332                 attr = pjmedia_sdp_attr_create(pool, "maxptime", pj_cstr(&stmp, tmp));
1333                 media->attr[media->attr_count++] = attr;
1334         }
1335
1336         /* Add the sendrecv attribute - we purposely don't keep track because pjmedia-sdp will automatically change our offer for us */
1337         attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr);
1338         attr->name = !session_media->locally_held ? STR_SENDRECV : STR_SENDONLY;
1339         media->attr[media->attr_count++] = attr;
1340
1341         /* If we've got rtcp-mux enabled, just unconditionally offer it in all SDPs */
1342         if (session->endpoint->media.rtcp_mux) {
1343                 attr = pjmedia_sdp_attr_create(pool, "rtcp-mux", NULL);
1344                 pjmedia_sdp_attr_add(&media->attr_count, media->attr, attr);
1345         }
1346
1347         /* Add the media stream to the SDP */
1348         sdp->media[sdp->media_count++] = media;
1349
1350         return 1;
1351 }
1352
1353 static int apply_negotiated_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
1354                                        const struct pjmedia_sdp_session *local, const struct pjmedia_sdp_media *local_stream,
1355                                        const struct pjmedia_sdp_session *remote, const struct pjmedia_sdp_media *remote_stream)
1356 {
1357         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
1358         enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
1359         char host[NI_MAXHOST];
1360         int fdno, res;
1361
1362         if (!session->channel) {
1363                 return 1;
1364         }
1365
1366         if (!local_stream->desc.port || !remote_stream->desc.port) {
1367                 return 1;
1368         }
1369
1370         /* Ensure incoming transport is compatible with the endpoint's configuration */
1371         if (!session->endpoint->media.rtp.use_received_transport &&
1372                 check_endpoint_media_transport(session->endpoint, remote_stream) == AST_SIP_MEDIA_TRANSPORT_INVALID) {
1373                 return -1;
1374         }
1375
1376         /* Create an RTP instance if need be */
1377         if (!session_media->rtp && create_rtp(session, session_media)) {
1378                 return -1;
1379         }
1380
1381         session_media->remote_rtcp_mux = (pjmedia_sdp_media_find_attr2(remote_stream, "rtcp-mux", NULL) != NULL);
1382         set_ice_components(session, session_media);
1383
1384         enable_rtcp(session, session_media, remote_stream);
1385
1386         res = setup_media_encryption(session, session_media, remote, remote_stream);
1387         if (!session->endpoint->media.rtp.encryption_optimistic && res) {
1388                 /* If optimistic encryption is disabled and crypto should have been enabled but was not
1389                  * this session must fail.
1390                  */
1391                 return -1;
1392         }
1393
1394         if (!remote_stream->conn && !remote->conn) {
1395                 return 1;
1396         }
1397
1398         ast_copy_pj_str(host, remote_stream->conn ? &remote_stream->conn->addr : &remote->conn->addr, sizeof(host));
1399
1400         /* Ensure that the address provided is valid */
1401         if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
1402                 /* The provided host was actually invalid so we error out this negotiation */
1403                 return -1;
1404         }
1405
1406         /* Apply connection information to the RTP instance */
1407         ast_sockaddr_set_port(addrs, remote_stream->desc.port);
1408         ast_rtp_instance_set_remote_address(session_media->rtp, addrs);
1409         if (set_caps(session, session_media, remote_stream, 0)) {
1410                 return 1;
1411         }
1412
1413         if ((fdno = media_type_to_fdno(media_type)) < 0) {
1414                 return -1;
1415         }
1416         ast_channel_set_fd(session->channel, fdno, ast_rtp_instance_fd(session_media->rtp, 0));
1417         if (!session->endpoint->media.rtcp_mux || !session_media->remote_rtcp_mux) {
1418                 ast_channel_set_fd(session->channel, fdno + 1, ast_rtp_instance_fd(session_media->rtp, 1));
1419         }
1420
1421         /* If ICE support is enabled find all the needed attributes */
1422         process_ice_attributes(session, session_media, remote, remote_stream);
1423
1424         /* Ensure the RTP instance is active */
1425         ast_rtp_instance_activate(session_media->rtp);
1426
1427         /* audio stream handles music on hold */
1428         if (media_type != AST_MEDIA_TYPE_AUDIO) {
1429                 if ((pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_FALSE)
1430                         && (session->inv_session->state == PJSIP_INV_STATE_CONFIRMED)) {
1431                         ast_queue_control(session->channel, AST_CONTROL_UPDATE_RTP_PEER);
1432                 }
1433                 return 1;
1434         }
1435
1436         if (ast_sockaddr_isnull(addrs) ||
1437                 ast_sockaddr_is_any(addrs) ||
1438                 pjmedia_sdp_media_find_attr2(remote_stream, "sendonly", NULL) ||
1439                 pjmedia_sdp_media_find_attr2(remote_stream, "inactive", NULL)) {
1440                 if (!session_media->remotely_held) {
1441                         /* The remote side has put us on hold */
1442                         ast_queue_hold(session->channel, session->endpoint->mohsuggest);
1443                         ast_rtp_instance_stop(session_media->rtp);
1444                         ast_queue_frame(session->channel, &ast_null_frame);
1445                         session_media->remotely_held = 1;
1446                 }
1447         } else if (session_media->remotely_held) {
1448                 /* The remote side has taken us off hold */
1449                 ast_queue_unhold(session->channel);
1450                 ast_queue_frame(session->channel, &ast_null_frame);
1451                 session_media->remotely_held = 0;
1452         } else if ((pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_FALSE)
1453                 && (session->inv_session->state == PJSIP_INV_STATE_CONFIRMED)) {
1454                 ast_queue_control(session->channel, AST_CONTROL_UPDATE_RTP_PEER);
1455         }
1456
1457         /* This purposely resets the encryption to the configured in case it gets added later */
1458         session_media->encryption = session->endpoint->media.rtp.encryption;
1459
1460         if (session->endpoint->media.rtp.keepalive > 0 &&
1461                         stream_to_media_type(session_media->stream_type) == AST_MEDIA_TYPE_AUDIO) {
1462                 ast_rtp_instance_set_keepalive(session_media->rtp, session->endpoint->media.rtp.keepalive);
1463                 /* Schedule the initial keepalive early in case this is being used to punch holes through
1464                  * a NAT. This way there won't be an awkward delay before media starts flowing in some
1465                  * scenarios.
1466                  */
1467                 AST_SCHED_DEL(sched, session_media->keepalive_sched_id);
1468                 session_media->keepalive_sched_id = ast_sched_add_variable(sched, 500, send_keepalive,
1469                         session_media, 1);
1470         }
1471
1472         /* As the channel lock is not held during this process the scheduled item won't block if
1473          * it is hanging up the channel at the same point we are applying this negotiated SDP.
1474          */
1475         AST_SCHED_DEL(sched, session_media->timeout_sched_id);
1476
1477         /* Due to the fact that we only ever have one scheduled timeout item for when we are both
1478          * off hold and on hold we don't need to store the two timeouts differently on the RTP
1479          * instance itself.
1480          */
1481         ast_rtp_instance_set_timeout(session_media->rtp, 0);
1482         if (session->endpoint->media.rtp.timeout && !session_media->remotely_held) {
1483                 ast_rtp_instance_set_timeout(session_media->rtp, session->endpoint->media.rtp.timeout);
1484         } else if (session->endpoint->media.rtp.timeout_hold && session_media->remotely_held) {
1485                 ast_rtp_instance_set_timeout(session_media->rtp, session->endpoint->media.rtp.timeout_hold);
1486         }
1487
1488         if (ast_rtp_instance_get_timeout(session_media->rtp)) {
1489                 session_media->timeout_sched_id = ast_sched_add_variable(sched,
1490                         ast_rtp_instance_get_timeout(session_media->rtp) * 1000, rtp_check_timeout,
1491                         session_media, 1);
1492         }
1493
1494         return 1;
1495 }
1496
1497 /*! \brief Function which updates the media stream with external media address, if applicable */
1498 static void change_outgoing_sdp_stream_media_address(pjsip_tx_data *tdata, struct pjmedia_sdp_media *stream, struct ast_sip_transport *transport)
1499 {
1500         RAII_VAR(struct ast_sip_transport_state *, transport_state, ast_sip_get_transport_state(ast_sorcery_object_get_id(transport)), ao2_cleanup);
1501         char host[NI_MAXHOST];
1502         struct ast_sockaddr addr = { { 0, } };
1503
1504         /* If the stream has been rejected there will be no connection line */
1505         if (!stream->conn || !transport_state) {
1506                 return;
1507         }
1508
1509         ast_copy_pj_str(host, &stream->conn->addr, sizeof(host));
1510         ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID);
1511
1512         /* Is the address within the SDP inside the same network? */
1513         if (transport_state->localnet
1514                 && ast_apply_ha(transport_state->localnet, &addr) == AST_SENSE_ALLOW) {
1515                 return;
1516         }
1517         ast_debug(5, "Setting media address to %s\n", transport->external_media_address);
1518         pj_strdup2(tdata->pool, &stream->conn->addr, transport->external_media_address);
1519 }
1520
1521 /*! \brief Function which stops the RTP instance */
1522 static void stream_stop(struct ast_sip_session_media *session_media)
1523 {
1524         if (!session_media->rtp) {
1525                 return;
1526         }
1527
1528         AST_SCHED_DEL(sched, session_media->keepalive_sched_id);
1529         AST_SCHED_DEL(sched, session_media->timeout_sched_id);
1530         ast_rtp_instance_stop(session_media->rtp);
1531 }
1532
1533 /*! \brief Function which destroys the RTP instance when session ends */
1534 static void stream_destroy(struct ast_sip_session_media *session_media)
1535 {
1536         if (session_media->rtp) {
1537                 stream_stop(session_media);
1538                 ast_rtp_instance_destroy(session_media->rtp);
1539         }
1540         session_media->rtp = NULL;
1541 }
1542
1543 /*! \brief SDP handler for 'audio' media stream */
1544 static struct ast_sip_session_sdp_handler audio_sdp_handler = {
1545         .id = STR_AUDIO,
1546         .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
1547         .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
1548         .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
1549         .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
1550         .stream_stop = stream_stop,
1551         .stream_destroy = stream_destroy,
1552 };
1553
1554 /*! \brief SDP handler for 'video' media stream */
1555 static struct ast_sip_session_sdp_handler video_sdp_handler = {
1556         .id = STR_VIDEO,
1557         .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
1558         .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
1559         .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
1560         .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
1561         .stream_stop = stream_stop,
1562         .stream_destroy = stream_destroy,
1563 };
1564
1565 static int video_info_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
1566 {
1567         struct pjsip_transaction *tsx;
1568         pjsip_tx_data *tdata;
1569
1570         if (!session->channel
1571                 || !ast_sip_is_content_type(&rdata->msg_info.msg->body->content_type,
1572                         "application",
1573                         "media_control+xml")) {
1574                 return 0;
1575         }
1576
1577         tsx = pjsip_rdata_get_tsx(rdata);
1578
1579         ast_queue_control(session->channel, AST_CONTROL_VIDUPDATE);
1580
1581         if (pjsip_dlg_create_response(session->inv_session->dlg, rdata, 200, NULL, &tdata) == PJ_SUCCESS) {
1582                 pjsip_dlg_send_response(session->inv_session->dlg, tsx, tdata);
1583         }
1584
1585         return 0;
1586 }
1587
1588 static struct ast_sip_session_supplement video_info_supplement = {
1589         .method = "INFO",
1590         .incoming_request = video_info_incoming_request,
1591 };
1592
1593 /*! \brief Unloads the sdp RTP/AVP module from Asterisk */
1594 static int unload_module(void)
1595 {
1596         ast_sip_session_unregister_supplement(&video_info_supplement);
1597         ast_sip_session_unregister_sdp_handler(&video_sdp_handler, STR_VIDEO);
1598         ast_sip_session_unregister_sdp_handler(&audio_sdp_handler, STR_AUDIO);
1599
1600         if (sched) {
1601                 ast_sched_context_destroy(sched);
1602         }
1603
1604         return 0;
1605 }
1606
1607 /*!
1608  * \brief Load the module
1609  *
1610  * Module loading including tests for configuration or dependencies.
1611  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1612  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1613  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
1614  * configuration file or other non-critical problem return
1615  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1616  */
1617 static int load_module(void)
1618 {
1619         CHECK_PJSIP_SESSION_MODULE_LOADED();
1620
1621         if (ast_check_ipv6()) {
1622                 ast_sockaddr_parse(&address_rtp, "::", 0);
1623         } else {
1624                 ast_sockaddr_parse(&address_rtp, "0.0.0.0", 0);
1625         }
1626
1627         if (!(sched = ast_sched_context_create())) {
1628                 ast_log(LOG_ERROR, "Unable to create scheduler context.\n");
1629                 goto end;
1630         }
1631
1632         if (ast_sched_start_thread(sched)) {
1633                 ast_log(LOG_ERROR, "Unable to create scheduler context thread.\n");
1634                 goto end;
1635         }
1636
1637         if (ast_sip_session_register_sdp_handler(&audio_sdp_handler, STR_AUDIO)) {
1638                 ast_log(LOG_ERROR, "Unable to register SDP handler for %s stream type\n", STR_AUDIO);
1639                 goto end;
1640         }
1641
1642         if (ast_sip_session_register_sdp_handler(&video_sdp_handler, STR_VIDEO)) {
1643                 ast_log(LOG_ERROR, "Unable to register SDP handler for %s stream type\n", STR_VIDEO);
1644                 goto end;
1645         }
1646
1647         ast_sip_session_register_supplement(&video_info_supplement);
1648
1649         return AST_MODULE_LOAD_SUCCESS;
1650 end:
1651         unload_module();
1652
1653         return AST_MODULE_LOAD_DECLINE;
1654 }
1655
1656 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP SDP RTP/AVP stream handler",
1657         .support_level = AST_MODULE_SUPPORT_CORE,
1658         .load = load_module,
1659         .unload = unload_module,
1660         .load_pri = AST_MODPRI_CHANNEL_DRIVER,
1661 );