97e365c103a7fde4fcd3609918ded2749453de97
[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         extern pj_bool_t pjsip_use_compact_form;
457         pjmedia_sdp_rtpmap rtpmap;
458         pjmedia_sdp_attr *attr = NULL;
459         char tmp[64];
460         enum ast_rtp_options options = session->endpoint->media.g726_non_standard ?
461                 AST_RTP_OPT_G726_NONSTANDARD : 0;
462
463         snprintf(tmp, sizeof(tmp), "%d", rtp_code);
464         pj_strdup2(pool, &media->desc.fmt[media->desc.fmt_count++], tmp);
465
466         if (rtp_code <= AST_RTP_PT_LAST_STATIC && pjsip_use_compact_form) {
467                 return NULL;
468         }
469
470         rtpmap.pt = media->desc.fmt[media->desc.fmt_count - 1];
471         rtpmap.clock_rate = ast_rtp_lookup_sample_rate2(asterisk_format, format, code);
472         pj_strdup2(pool, &rtpmap.enc_name, ast_rtp_lookup_mime_subtype2(asterisk_format, format, code, options));
473         if (!pj_stricmp2(&rtpmap.enc_name, "opus")) {
474                 pj_cstr(&rtpmap.param, "2");
475         } else {
476                 pj_cstr(&rtpmap.param, NULL);
477         }
478
479         pjmedia_sdp_rtpmap_to_attr(pool, &rtpmap, &attr);
480
481         return attr;
482 }
483
484 static pjmedia_sdp_attr* generate_fmtp_attr(pj_pool_t *pool, struct ast_format *format, int rtp_code)
485 {
486         struct ast_str *fmtp0 = ast_str_alloca(256);
487         pj_str_t fmtp1;
488         pjmedia_sdp_attr *attr = NULL;
489         char *tmp;
490
491         ast_format_generate_sdp_fmtp(format, rtp_code, &fmtp0);
492         if (ast_str_strlen(fmtp0)) {
493                 tmp = ast_str_buffer(fmtp0) + ast_str_strlen(fmtp0) - 1;
494                 /* remove any carriage return line feeds */
495                 while (*tmp == '\r' || *tmp == '\n') --tmp;
496                 *++tmp = '\0';
497                 /* ast...generate gives us everything, just need value */
498                 tmp = strchr(ast_str_buffer(fmtp0), ':');
499                 if (tmp && tmp[1] != '\0') {
500                         fmtp1 = pj_str(tmp + 1);
501                 } else {
502                         fmtp1 = pj_str(ast_str_buffer(fmtp0));
503                 }
504                 attr = pjmedia_sdp_attr_create(pool, "fmtp", &fmtp1);
505         }
506         return attr;
507 }
508
509 /*! \brief Function which adds ICE attributes to a media stream */
510 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)
511 {
512         struct ast_rtp_engine_ice *ice;
513         struct ao2_container *candidates;
514         const char *username, *password;
515         pj_str_t stmp;
516         pjmedia_sdp_attr *attr;
517         struct ao2_iterator it_candidates;
518         struct ast_rtp_engine_ice_candidate *candidate;
519
520         if (!session->endpoint->media.rtp.ice_support || !(ice = ast_rtp_instance_get_ice(session_media->rtp)) ||
521                 !(candidates = ice->get_local_candidates(session_media->rtp))) {
522                 return;
523         }
524
525         if ((username = ice->get_ufrag(session_media->rtp))) {
526                 attr = pjmedia_sdp_attr_create(pool, "ice-ufrag", pj_cstr(&stmp, username));
527                 media->attr[media->attr_count++] = attr;
528         }
529
530         if ((password = ice->get_password(session_media->rtp))) {
531                 attr = pjmedia_sdp_attr_create(pool, "ice-pwd", pj_cstr(&stmp, password));
532                 media->attr[media->attr_count++] = attr;
533         }
534
535         it_candidates = ao2_iterator_init(candidates, 0);
536         for (; (candidate = ao2_iterator_next(&it_candidates)); ao2_ref(candidate, -1)) {
537                 struct ast_str *attr_candidate = ast_str_create(128);
538
539                 ast_str_set(&attr_candidate, -1, "%s %u %s %d %s ", candidate->foundation, candidate->id, candidate->transport,
540                                         candidate->priority, ast_sockaddr_stringify_addr_remote(&candidate->address));
541                 ast_str_append(&attr_candidate, -1, "%s typ ", ast_sockaddr_stringify_port(&candidate->address));
542
543                 switch (candidate->type) {
544                         case AST_RTP_ICE_CANDIDATE_TYPE_HOST:
545                                 ast_str_append(&attr_candidate, -1, "host");
546                                 break;
547                         case AST_RTP_ICE_CANDIDATE_TYPE_SRFLX:
548                                 ast_str_append(&attr_candidate, -1, "srflx");
549                                 break;
550                         case AST_RTP_ICE_CANDIDATE_TYPE_RELAYED:
551                                 ast_str_append(&attr_candidate, -1, "relay");
552                                 break;
553                 }
554
555                 if (!ast_sockaddr_isnull(&candidate->relay_address)) {
556                         ast_str_append(&attr_candidate, -1, " raddr %s rport", ast_sockaddr_stringify_addr_remote(&candidate->relay_address));
557                         ast_str_append(&attr_candidate, -1, " %s", ast_sockaddr_stringify_port(&candidate->relay_address));
558                 }
559
560                 attr = pjmedia_sdp_attr_create(pool, "candidate", pj_cstr(&stmp, ast_str_buffer(attr_candidate)));
561                 media->attr[media->attr_count++] = attr;
562
563                 ast_free(attr_candidate);
564         }
565
566         ao2_iterator_destroy(&it_candidates);
567         ao2_ref(candidates, -1);
568 }
569
570 /*! \brief Function which processes ICE attributes in an audio stream */
571 static void process_ice_attributes(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
572                                    const struct pjmedia_sdp_session *remote, const struct pjmedia_sdp_media *remote_stream)
573 {
574         struct ast_rtp_engine_ice *ice;
575         const pjmedia_sdp_attr *attr;
576         char attr_value[256];
577         unsigned int attr_i;
578
579         /* If ICE support is not enabled or available exit early */
580         if (!session->endpoint->media.rtp.ice_support || !(ice = ast_rtp_instance_get_ice(session_media->rtp))) {
581                 return;
582         }
583
584         attr = pjmedia_sdp_media_find_attr2(remote_stream, "ice-ufrag", NULL);
585         if (!attr) {
586                 attr = pjmedia_sdp_attr_find2(remote->attr_count, remote->attr, "ice-ufrag", NULL);
587         }
588         if (attr) {
589                 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
590                 ice->set_authentication(session_media->rtp, attr_value, NULL);
591         } else {
592                 return;
593         }
594
595         attr = pjmedia_sdp_media_find_attr2(remote_stream, "ice-pwd", NULL);
596         if (!attr) {
597                 attr = pjmedia_sdp_attr_find2(remote->attr_count, remote->attr, "ice-pwd", NULL);
598         }
599         if (attr) {
600                 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
601                 ice->set_authentication(session_media->rtp, NULL, attr_value);
602         } else {
603                 return;
604         }
605
606         if (pjmedia_sdp_media_find_attr2(remote_stream, "ice-lite", NULL)) {
607                 ice->ice_lite(session_media->rtp);
608         }
609
610         /* Find all of the candidates */
611         for (attr_i = 0; attr_i < remote_stream->attr_count; ++attr_i) {
612                 char foundation[32], transport[32], address[PJ_INET6_ADDRSTRLEN + 1], cand_type[6], relay_address[PJ_INET6_ADDRSTRLEN + 1] = "";
613                 unsigned int port, relay_port = 0;
614                 struct ast_rtp_engine_ice_candidate candidate = { 0, };
615
616                 attr = remote_stream->attr[attr_i];
617
618                 /* If this is not a candidate line skip it */
619                 if (pj_strcmp2(&attr->name, "candidate")) {
620                         continue;
621                 }
622
623                 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
624
625                 if (sscanf(attr_value, "%31s %30u %31s %30u %46s %30u typ %5s %*s %23s %*s %30u", foundation, &candidate.id, transport,
626                         (unsigned *)&candidate.priority, address, &port, cand_type, relay_address, &relay_port) < 7) {
627                         /* Candidate did not parse properly */
628                         continue;
629                 }
630
631                 if (session->endpoint->media.rtcp_mux && session_media->remote_rtcp_mux && candidate.id > 1) {
632                         /* Remote side may have offered RTP and RTCP candidates. However, if we're using RTCP MUX,
633                          * then we should ignore RTCP candidates.
634                          */
635                         continue;
636                 }
637
638                 candidate.foundation = foundation;
639                 candidate.transport = transport;
640
641                 ast_sockaddr_parse(&candidate.address, address, PARSE_PORT_FORBID);
642                 ast_sockaddr_set_port(&candidate.address, port);
643
644                 if (!strcasecmp(cand_type, "host")) {
645                         candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
646                 } else if (!strcasecmp(cand_type, "srflx")) {
647                         candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
648                 } else if (!strcasecmp(cand_type, "relay")) {
649                         candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
650                 } else {
651                         continue;
652                 }
653
654                 if (!ast_strlen_zero(relay_address)) {
655                         ast_sockaddr_parse(&candidate.relay_address, relay_address, PARSE_PORT_FORBID);
656                 }
657
658                 if (relay_port) {
659                         ast_sockaddr_set_port(&candidate.relay_address, relay_port);
660                 }
661
662                 ice->add_remote_candidate(session_media->rtp, &candidate);
663         }
664
665         ice->set_role(session_media->rtp, pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_TRUE ?
666                 AST_RTP_ICE_ROLE_CONTROLLING : AST_RTP_ICE_ROLE_CONTROLLED);
667         ice->start(session_media->rtp);
668 }
669
670 /*! \brief figure out if media stream has crypto lines for sdes */
671 static int media_stream_has_crypto(const struct pjmedia_sdp_media *stream)
672 {
673         int i;
674
675         for (i = 0; i < stream->attr_count; i++) {
676                 pjmedia_sdp_attr *attr;
677
678                 /* check the stream for the required crypto attribute */
679                 attr = stream->attr[i];
680                 if (pj_strcmp2(&attr->name, "crypto")) {
681                         continue;
682                 }
683
684                 return 1;
685         }
686
687         return 0;
688 }
689
690 /*! \brief figure out media transport encryption type from the media transport string */
691 static enum ast_sip_session_media_encryption get_media_encryption_type(pj_str_t transport,
692         const struct pjmedia_sdp_media *stream, unsigned int *optimistic)
693 {
694         RAII_VAR(char *, transport_str, ast_strndup(transport.ptr, transport.slen), ast_free);
695
696         *optimistic = 0;
697
698         if (!transport_str) {
699                 return AST_SIP_MEDIA_TRANSPORT_INVALID;
700         }
701         if (strstr(transport_str, "UDP/TLS")) {
702                 return AST_SIP_MEDIA_ENCRYPT_DTLS;
703         } else if (strstr(transport_str, "SAVP")) {
704                 return AST_SIP_MEDIA_ENCRYPT_SDES;
705         } else if (media_stream_has_crypto(stream)) {
706                 *optimistic = 1;
707                 return AST_SIP_MEDIA_ENCRYPT_SDES;
708         } else {
709                 return AST_SIP_MEDIA_ENCRYPT_NONE;
710         }
711 }
712
713 /*!
714  * \brief Checks whether the encryption offered in SDP is compatible with the endpoint's configuration
715  * \internal
716  *
717  * \param endpoint_encryption Media encryption configured for the endpoint
718  * \param stream pjmedia_sdp_media stream description
719  *
720  * \retval AST_SIP_MEDIA_TRANSPORT_INVALID on encryption mismatch
721  * \retval The encryption requested in the SDP
722  */
723 static enum ast_sip_session_media_encryption check_endpoint_media_transport(
724         struct ast_sip_endpoint *endpoint,
725         const struct pjmedia_sdp_media *stream)
726 {
727         enum ast_sip_session_media_encryption incoming_encryption;
728         char transport_end = stream->desc.transport.ptr[stream->desc.transport.slen - 1];
729         unsigned int optimistic;
730
731         if ((transport_end == 'F' && !endpoint->media.rtp.use_avpf)
732                 || (transport_end != 'F' && endpoint->media.rtp.use_avpf)) {
733                 return AST_SIP_MEDIA_TRANSPORT_INVALID;
734         }
735
736         incoming_encryption = get_media_encryption_type(stream->desc.transport, stream, &optimistic);
737
738         if (incoming_encryption == endpoint->media.rtp.encryption) {
739                 return incoming_encryption;
740         }
741
742         if (endpoint->media.rtp.force_avp ||
743                 endpoint->media.rtp.encryption_optimistic) {
744                 return incoming_encryption;
745         }
746
747         /* If an optimistic offer has been made but encryption is not enabled consider it as having
748          * no offer of crypto at all instead of invalid so the session proceeds.
749          */
750         if (optimistic) {
751                 return AST_SIP_MEDIA_ENCRYPT_NONE;
752         }
753
754         return AST_SIP_MEDIA_TRANSPORT_INVALID;
755 }
756
757 static int setup_srtp(struct ast_sip_session_media *session_media)
758 {
759         if (!session_media->srtp) {
760                 session_media->srtp = ast_sdp_srtp_alloc();
761                 if (!session_media->srtp) {
762                         return -1;
763                 }
764         }
765
766         if (!session_media->srtp->crypto) {
767                 session_media->srtp->crypto = ast_sdp_crypto_alloc();
768                 if (!session_media->srtp->crypto) {
769                         return -1;
770                 }
771         }
772
773         return 0;
774 }
775
776 static int setup_dtls_srtp(struct ast_sip_session *session,
777         struct ast_sip_session_media *session_media)
778 {
779         struct ast_rtp_engine_dtls *dtls;
780
781         if (!session->endpoint->media.rtp.dtls_cfg.enabled || !session_media->rtp) {
782                 return -1;
783         }
784
785         dtls = ast_rtp_instance_get_dtls(session_media->rtp);
786         if (!dtls) {
787                 return -1;
788         }
789
790         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);
791         if (dtls->set_configuration(session_media->rtp, &session->endpoint->media.rtp.dtls_cfg)) {
792                 ast_log(LOG_ERROR, "Attempted to set an invalid DTLS-SRTP configuration on RTP instance '%p'\n",
793                         session_media->rtp);
794                 return -1;
795         }
796
797         if (setup_srtp(session_media)) {
798                 return -1;
799         }
800         return 0;
801 }
802
803 static void apply_dtls_attrib(struct ast_sip_session_media *session_media,
804         pjmedia_sdp_attr *attr)
805 {
806         struct ast_rtp_engine_dtls *dtls = ast_rtp_instance_get_dtls(session_media->rtp);
807         pj_str_t *value;
808
809         if (!attr->value.ptr || !dtls) {
810                 return;
811         }
812
813         value = pj_strtrim(&attr->value);
814
815         if (!pj_strcmp2(&attr->name, "setup")) {
816                 if (!pj_stricmp2(value, "active")) {
817                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_ACTIVE);
818                 } else if (!pj_stricmp2(value, "passive")) {
819                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_PASSIVE);
820                 } else if (!pj_stricmp2(value, "actpass")) {
821                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_ACTPASS);
822                 } else if (!pj_stricmp2(value, "holdconn")) {
823                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_HOLDCONN);
824                 } else {
825                         ast_log(LOG_WARNING, "Unsupported setup attribute value '%*s'\n", (int)value->slen, value->ptr);
826                 }
827         } else if (!pj_strcmp2(&attr->name, "connection")) {
828                 if (!pj_stricmp2(value, "new")) {
829                         dtls->reset(session_media->rtp);
830                 } else if (!pj_stricmp2(value, "existing")) {
831                         /* Do nothing */
832                 } else {
833                         ast_log(LOG_WARNING, "Unsupported connection attribute value '%*s'\n", (int)value->slen, value->ptr);
834                 }
835         } else if (!pj_strcmp2(&attr->name, "fingerprint")) {
836                 char hash_value[256], hash[32];
837                 char fingerprint_text[value->slen + 1];
838                 ast_copy_pj_str(fingerprint_text, value, sizeof(fingerprint_text));
839                         if (sscanf(fingerprint_text, "%31s %255s", hash, hash_value) == 2) {
840                         if (!strcasecmp(hash, "sha-1")) {
841                                 dtls->set_fingerprint(session_media->rtp, AST_RTP_DTLS_HASH_SHA1, hash_value);
842                         } else if (!strcasecmp(hash, "sha-256")) {
843                                 dtls->set_fingerprint(session_media->rtp, AST_RTP_DTLS_HASH_SHA256, hash_value);
844                         } else {
845                                 ast_log(LOG_WARNING, "Unsupported fingerprint hash type '%s'\n",
846                                 hash);
847                         }
848                 }
849         }
850 }
851
852 static int parse_dtls_attrib(struct ast_sip_session_media *session_media,
853         const struct pjmedia_sdp_session *sdp,
854         const struct pjmedia_sdp_media *stream)
855 {
856         int i;
857
858         for (i = 0; i < sdp->attr_count; i++) {
859                 apply_dtls_attrib(session_media, sdp->attr[i]);
860         }
861
862         for (i = 0; i < stream->attr_count; i++) {
863                 apply_dtls_attrib(session_media, stream->attr[i]);
864         }
865
866         ast_set_flag(session_media->srtp, AST_SRTP_CRYPTO_OFFER_OK);
867
868         return 0;
869 }
870
871 static int setup_sdes_srtp(struct ast_sip_session_media *session_media,
872         const struct pjmedia_sdp_media *stream)
873 {
874         int i;
875
876         for (i = 0; i < stream->attr_count; i++) {
877                 pjmedia_sdp_attr *attr;
878                 RAII_VAR(char *, crypto_str, NULL, ast_free);
879
880                 /* check the stream for the required crypto attribute */
881                 attr = stream->attr[i];
882                 if (pj_strcmp2(&attr->name, "crypto")) {
883                         continue;
884                 }
885
886                 crypto_str = ast_strndup(attr->value.ptr, attr->value.slen);
887                 if (!crypto_str) {
888                         return -1;
889                 }
890
891                 if (setup_srtp(session_media)) {
892                         return -1;
893                 }
894
895                 if (!ast_sdp_crypto_process(session_media->rtp, session_media->srtp, crypto_str)) {
896                         /* found a valid crypto attribute */
897                         return 0;
898                 }
899
900                 ast_debug(1, "Ignoring crypto offer with unsupported parameters: %s\n", crypto_str);
901         }
902
903         /* no usable crypto attributes found */
904         return -1;
905 }
906
907 static int setup_media_encryption(struct ast_sip_session *session,
908         struct ast_sip_session_media *session_media,
909         const struct pjmedia_sdp_session *sdp,
910         const struct pjmedia_sdp_media *stream)
911 {
912         switch (session_media->encryption) {
913         case AST_SIP_MEDIA_ENCRYPT_SDES:
914                 if (setup_sdes_srtp(session_media, stream)) {
915                         return -1;
916                 }
917                 break;
918         case AST_SIP_MEDIA_ENCRYPT_DTLS:
919                 if (setup_dtls_srtp(session, session_media)) {
920                         return -1;
921                 }
922                 if (parse_dtls_attrib(session_media, sdp, stream)) {
923                         return -1;
924                 }
925                 break;
926         case AST_SIP_MEDIA_TRANSPORT_INVALID:
927         case AST_SIP_MEDIA_ENCRYPT_NONE:
928                 break;
929         }
930
931         return 0;
932 }
933
934 static void set_ice_components(struct ast_sip_session *session, struct ast_sip_session_media *session_media)
935 {
936         struct ast_rtp_engine_ice *ice;
937
938         ast_assert(session_media->rtp != NULL);
939
940         ice = ast_rtp_instance_get_ice(session_media->rtp);
941         if (!session->endpoint->media.rtp.ice_support || !ice) {
942                 return;
943         }
944
945         if (session->endpoint->media.rtcp_mux && session_media->remote_rtcp_mux) {
946                 /* We both support RTCP mux. Only one ICE component necessary */
947                 ice->change_components(session_media->rtp, 1);
948         } else {
949                 /* They either don't support RTCP mux or we don't know if they do yet. */
950                 ice->change_components(session_media->rtp, 2);
951         }
952 }
953
954 /*! \brief Function which negotiates an incoming media stream */
955 static int negotiate_incoming_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
956                                          const struct pjmedia_sdp_session *sdp, const struct pjmedia_sdp_media *stream)
957 {
958         char host[NI_MAXHOST];
959         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
960         enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
961         enum ast_sip_session_media_encryption encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
962         int res;
963
964         /* If port is 0, ignore this media stream */
965         if (!stream->desc.port) {
966                 ast_debug(3, "Media stream '%s' is already declined\n", session_media->stream_type);
967                 return 0;
968         }
969
970         /* If no type formats have been configured reject this stream */
971         if (!ast_format_cap_has_type(session->endpoint->media.codecs, media_type)) {
972                 ast_debug(3, "Endpoint has no codecs for media type '%s', declining stream\n", session_media->stream_type);
973                 return 0;
974         }
975
976         /* Ensure incoming transport is compatible with the endpoint's configuration */
977         if (!session->endpoint->media.rtp.use_received_transport) {
978                 encryption = check_endpoint_media_transport(session->endpoint, stream);
979
980                 if (encryption == AST_SIP_MEDIA_TRANSPORT_INVALID) {
981                         return -1;
982                 }
983         }
984
985         ast_copy_pj_str(host, stream->conn ? &stream->conn->addr : &sdp->conn->addr, sizeof(host));
986
987         /* Ensure that the address provided is valid */
988         if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
989                 /* The provided host was actually invalid so we error out this negotiation */
990                 return -1;
991         }
992
993         /* Using the connection information create an appropriate RTP instance */
994         if (!session_media->rtp && create_rtp(session, session_media)) {
995                 return -1;
996         }
997
998         session_media->remote_rtcp_mux = (pjmedia_sdp_media_find_attr2(stream, "rtcp-mux", NULL) != NULL);
999         set_ice_components(session, session_media);
1000
1001         enable_rtcp(session, session_media, stream);
1002
1003         res = setup_media_encryption(session, session_media, sdp, stream);
1004         if (res) {
1005                 if (!session->endpoint->media.rtp.encryption_optimistic ||
1006                         !pj_strncmp2(&stream->desc.transport, "RTP/SAVP", 8)) {
1007                         /* If optimistic encryption is disabled and crypto should have been enabled
1008                          * but was not this session must fail. This must also fail if crypto was
1009                          * required in the offer but could not be set up.
1010                          */
1011                         return -1;
1012                 }
1013                 /* There is no encryption, sad. */
1014                 session_media->encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
1015         }
1016
1017         /* If we've been explicitly configured to use the received transport OR if
1018          * encryption is on and crypto is present use the received transport.
1019          * This is done in case of optimistic because it may come in as RTP/AVP or RTP/SAVP depending
1020          * on the configuration of the remote endpoint (optimistic themselves or mandatory).
1021          */
1022         if ((session->endpoint->media.rtp.use_received_transport) ||
1023                 ((encryption == AST_SIP_MEDIA_ENCRYPT_SDES) && !res)) {
1024                 pj_strdup(session->inv_session->pool, &session_media->transport, &stream->desc.transport);
1025         }
1026
1027         if (set_caps(session, session_media, stream, 1)) {
1028                 return 0;
1029         }
1030         return 1;
1031 }
1032
1033 static int add_crypto_to_stream(struct ast_sip_session *session,
1034         struct ast_sip_session_media *session_media,
1035         pj_pool_t *pool, pjmedia_sdp_media *media)
1036 {
1037         pj_str_t stmp;
1038         pjmedia_sdp_attr *attr;
1039         enum ast_rtp_dtls_hash hash;
1040         const char *crypto_attribute;
1041         struct ast_rtp_engine_dtls *dtls;
1042         struct ast_sdp_srtp *tmp;
1043         static const pj_str_t STR_NEW = { "new", 3 };
1044         static const pj_str_t STR_EXISTING = { "existing", 8 };
1045         static const pj_str_t STR_ACTIVE = { "active", 6 };
1046         static const pj_str_t STR_PASSIVE = { "passive", 7 };
1047         static const pj_str_t STR_ACTPASS = { "actpass", 7 };
1048         static const pj_str_t STR_HOLDCONN = { "holdconn", 8 };
1049
1050         switch (session_media->encryption) {
1051         case AST_SIP_MEDIA_ENCRYPT_NONE:
1052         case AST_SIP_MEDIA_TRANSPORT_INVALID:
1053                 break;
1054         case AST_SIP_MEDIA_ENCRYPT_SDES:
1055                 if (!session_media->srtp) {
1056                         session_media->srtp = ast_sdp_srtp_alloc();
1057                         if (!session_media->srtp) {
1058                                 return -1;
1059                         }
1060                 }
1061
1062                 tmp = session_media->srtp;
1063
1064                 do {
1065                         crypto_attribute = ast_sdp_srtp_get_attrib(tmp,
1066                                 0 /* DTLS running? No */,
1067                                 session->endpoint->media.rtp.srtp_tag_32 /* 32 byte tag length? */);
1068                         if (!crypto_attribute) {
1069                                 /* No crypto attribute to add, bad news */
1070                                 return -1;
1071                         }
1072
1073                         attr = pjmedia_sdp_attr_create(pool, "crypto",
1074                                 pj_cstr(&stmp, crypto_attribute));
1075                         media->attr[media->attr_count++] = attr;
1076                 } while ((tmp = AST_LIST_NEXT(tmp, sdp_srtp_list)));
1077
1078                 break;
1079         case AST_SIP_MEDIA_ENCRYPT_DTLS:
1080                 if (setup_dtls_srtp(session, session_media)) {
1081                         return -1;
1082                 }
1083
1084                 dtls = ast_rtp_instance_get_dtls(session_media->rtp);
1085                 if (!dtls) {
1086                         return -1;
1087                 }
1088
1089                 switch (dtls->get_connection(session_media->rtp)) {
1090                 case AST_RTP_DTLS_CONNECTION_NEW:
1091                         attr = pjmedia_sdp_attr_create(pool, "connection", &STR_NEW);
1092                         media->attr[media->attr_count++] = attr;
1093                         break;
1094                 case AST_RTP_DTLS_CONNECTION_EXISTING:
1095                         attr = pjmedia_sdp_attr_create(pool, "connection", &STR_EXISTING);
1096                         media->attr[media->attr_count++] = attr;
1097                         break;
1098                 default:
1099                         break;
1100                 }
1101
1102                 switch (dtls->get_setup(session_media->rtp)) {
1103                 case AST_RTP_DTLS_SETUP_ACTIVE:
1104                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_ACTIVE);
1105                         media->attr[media->attr_count++] = attr;
1106                         break;
1107                 case AST_RTP_DTLS_SETUP_PASSIVE:
1108                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_PASSIVE);
1109                         media->attr[media->attr_count++] = attr;
1110                         break;
1111                 case AST_RTP_DTLS_SETUP_ACTPASS:
1112                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_ACTPASS);
1113                         media->attr[media->attr_count++] = attr;
1114                         break;
1115                 case AST_RTP_DTLS_SETUP_HOLDCONN:
1116                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_HOLDCONN);
1117                         media->attr[media->attr_count++] = attr;
1118                         break;
1119                 default:
1120                         break;
1121                 }
1122
1123                 hash = dtls->get_fingerprint_hash(session_media->rtp);
1124                 crypto_attribute = dtls->get_fingerprint(session_media->rtp);
1125                 if (crypto_attribute && (hash == AST_RTP_DTLS_HASH_SHA1 || hash == AST_RTP_DTLS_HASH_SHA256)) {
1126                         RAII_VAR(struct ast_str *, fingerprint, ast_str_create(64), ast_free);
1127                         if (!fingerprint) {
1128                                 return -1;
1129                         }
1130
1131                         if (hash == AST_RTP_DTLS_HASH_SHA1) {
1132                                 ast_str_set(&fingerprint, 0, "SHA-1 %s", crypto_attribute);
1133                         } else {
1134                                 ast_str_set(&fingerprint, 0, "SHA-256 %s", crypto_attribute);
1135                         }
1136
1137                         attr = pjmedia_sdp_attr_create(pool, "fingerprint", pj_cstr(&stmp, ast_str_buffer(fingerprint)));
1138                         media->attr[media->attr_count++] = attr;
1139                 }
1140                 break;
1141         }
1142
1143         return 0;
1144 }
1145
1146 /*! \brief Function which creates an outgoing stream */
1147 static int create_outgoing_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
1148                                       struct pjmedia_sdp_session *sdp)
1149 {
1150         pj_pool_t *pool = session->inv_session->pool_prov;
1151         static const pj_str_t STR_IN = { "IN", 2 };
1152         static const pj_str_t STR_IP4 = { "IP4", 3};
1153         static const pj_str_t STR_IP6 = { "IP6", 3};
1154         static const pj_str_t STR_SENDRECV = { "sendrecv", 8 };
1155         static const pj_str_t STR_SENDONLY = { "sendonly", 8 };
1156         pjmedia_sdp_media *media;
1157         const char *hostip = NULL;
1158         struct ast_sockaddr addr;
1159         char tmp[512];
1160         pj_str_t stmp;
1161         pjmedia_sdp_attr *attr;
1162         int index = 0;
1163         int noncodec = (session->endpoint->dtmf == AST_SIP_DTMF_RFC_4733 || session->endpoint->dtmf == AST_SIP_DTMF_AUTO) ? AST_RTP_DTMF : 0;
1164         int min_packet_size = 0, max_packet_size = 0;
1165         int rtp_code;
1166         RAII_VAR(struct ast_format_cap *, caps, NULL, ao2_cleanup);
1167         enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
1168         int use_override_prefs = ast_format_cap_count(session->req_caps);
1169
1170         int direct_media_enabled = !ast_sockaddr_isnull(&session_media->direct_media_addr) &&
1171                 ast_format_cap_count(session->direct_media_cap);
1172
1173         if ((use_override_prefs && !ast_format_cap_has_type(session->req_caps, media_type)) ||
1174             (!use_override_prefs && !ast_format_cap_has_type(session->endpoint->media.codecs, media_type))) {
1175                 /* If no type formats are configured don't add a stream */
1176                 return 0;
1177         } else if (!session_media->rtp && create_rtp(session, session_media)) {
1178                 return -1;
1179         }
1180
1181         set_ice_components(session, session_media);
1182         enable_rtcp(session, session_media, NULL);
1183
1184         if (!(media = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_media))) ||
1185                 !(media->conn = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_conn)))) {
1186                 return -1;
1187         }
1188
1189         if (add_crypto_to_stream(session, session_media, pool, media)) {
1190                 return -1;
1191         }
1192
1193         media->desc.media = pj_str(session_media->stream_type);
1194         if (pj_strlen(&session_media->transport)) {
1195                 /* If a transport has already been specified use it */
1196                 media->desc.transport = session_media->transport;
1197         } else {
1198                 media->desc.transport = pj_str(ast_sdp_get_rtp_profile(
1199                         /* Optimistic encryption places crypto in the normal RTP/AVP profile */
1200                         !session->endpoint->media.rtp.encryption_optimistic &&
1201                                 (session_media->encryption == AST_SIP_MEDIA_ENCRYPT_SDES),
1202                         session_media->rtp, session->endpoint->media.rtp.use_avpf,
1203                         session->endpoint->media.rtp.force_avp));
1204         }
1205
1206         /* Add connection level details */
1207         if (direct_media_enabled) {
1208                 hostip = ast_sockaddr_stringify_fmt(&session_media->direct_media_addr, AST_SOCKADDR_STR_ADDR);
1209         } else if (ast_strlen_zero(session->endpoint->media.address)) {
1210                 hostip = ast_sip_get_host_ip_string(session->endpoint->media.rtp.ipv6 ? pj_AF_INET6() : pj_AF_INET());
1211         } else {
1212                 hostip = session->endpoint->media.address;
1213         }
1214
1215         if (ast_strlen_zero(hostip)) {
1216                 ast_log(LOG_ERROR, "No local host IP available for stream %s\n", session_media->stream_type);
1217                 return -1;
1218         }
1219
1220         media->conn->net_type = STR_IN;
1221         /* Assume that the connection will use IPv4 until proven otherwise */
1222         media->conn->addr_type = STR_IP4;
1223         pj_strdup2(pool, &media->conn->addr, hostip);
1224
1225         if (!ast_strlen_zero(session->endpoint->media.address)) {
1226                 pj_sockaddr ip;
1227
1228                 if ((pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &media->conn->addr, &ip) == PJ_SUCCESS) &&
1229                         (ip.addr.sa_family == pj_AF_INET6())) {
1230                         media->conn->addr_type = STR_IP6;
1231                 }
1232         }
1233
1234         ast_rtp_instance_get_local_address(session_media->rtp, &addr);
1235         media->desc.port = direct_media_enabled ? ast_sockaddr_port(&session_media->direct_media_addr) : (pj_uint16_t) ast_sockaddr_port(&addr);
1236         media->desc.port_count = 1;
1237
1238         /* Add ICE attributes and candidates */
1239         add_ice_to_stream(session, session_media, pool, media);
1240
1241         if (!(caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1242                 ast_log(LOG_ERROR, "Failed to allocate %s capabilities\n", session_media->stream_type);
1243                 return -1;
1244         }
1245
1246         if (direct_media_enabled) {
1247                 ast_format_cap_get_compatible(session->endpoint->media.codecs, session->direct_media_cap, caps);
1248         } else if (!ast_format_cap_count(session->req_caps) ||
1249                 !ast_format_cap_iscompatible(session->req_caps, session->endpoint->media.codecs)) {
1250                 ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, media_type);
1251         } else {
1252                 ast_format_cap_append_from_cap(caps, session->req_caps, media_type);
1253         }
1254
1255         for (index = 0; index < ast_format_cap_count(caps); ++index) {
1256                 struct ast_format *format = ast_format_cap_get_format(caps, index);
1257
1258                 if (ast_format_get_type(format) != media_type) {
1259                         ao2_ref(format, -1);
1260                         continue;
1261                 }
1262
1263                 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(session_media->rtp), 1, format, 0)) == -1) {
1264                         ast_log(LOG_WARNING,"Unable to get rtp codec payload code for %s\n", ast_format_get_name(format));
1265                         ao2_ref(format, -1);
1266                         continue;
1267                 }
1268
1269                 if ((attr = generate_rtpmap_attr(session, media, pool, rtp_code, 1, format, 0))) {
1270                         media->attr[media->attr_count++] = attr;
1271                 }
1272
1273                 if ((attr = generate_fmtp_attr(pool, format, rtp_code))) {
1274                         media->attr[media->attr_count++] = attr;
1275                 }
1276
1277                 if (ast_format_get_maximum_ms(format) &&
1278                         ((ast_format_get_maximum_ms(format) < max_packet_size) || !max_packet_size)) {
1279                         max_packet_size = ast_format_get_maximum_ms(format);
1280                 }
1281                 ao2_ref(format, -1);
1282
1283                 if (media->desc.fmt_count == PJMEDIA_MAX_SDP_FMT) {
1284                         break;
1285                 }
1286         }
1287
1288         /* Add non-codec formats */
1289         if (media_type != AST_MEDIA_TYPE_VIDEO && media->desc.fmt_count < PJMEDIA_MAX_SDP_FMT) {
1290                 for (index = 1LL; index <= AST_RTP_MAX; index <<= 1) {
1291                         if (!(noncodec & index)) {
1292                                 continue;
1293                         }
1294                         rtp_code = ast_rtp_codecs_payload_code(
1295                                 ast_rtp_instance_get_codecs(session_media->rtp), 0, NULL, index);
1296                         if (rtp_code == -1) {
1297                                 continue;
1298                         }
1299
1300                         if ((attr = generate_rtpmap_attr(session, media, pool, rtp_code, 0, NULL, index))) {
1301                                 media->attr[media->attr_count++] = attr;
1302                         }
1303
1304                         if (index == AST_RTP_DTMF) {
1305                                 snprintf(tmp, sizeof(tmp), "%d 0-16", rtp_code);
1306                                 attr = pjmedia_sdp_attr_create(pool, "fmtp", pj_cstr(&stmp, tmp));
1307                                 media->attr[media->attr_count++] = attr;
1308                         }
1309
1310                         if (media->desc.fmt_count == PJMEDIA_MAX_SDP_FMT) {
1311                                 break;
1312                         }
1313                 }
1314         }
1315
1316         /* If no formats were actually added to the media stream don't add it to the SDP */
1317         if (!media->desc.fmt_count) {
1318                 return 1;
1319         }
1320
1321         /* If ptime is set add it as an attribute */
1322         min_packet_size = ast_rtp_codecs_get_framing(ast_rtp_instance_get_codecs(session_media->rtp));
1323         if (!min_packet_size) {
1324                 min_packet_size = ast_format_cap_get_framing(caps);
1325         }
1326         if (min_packet_size) {
1327                 snprintf(tmp, sizeof(tmp), "%d", min_packet_size);
1328                 attr = pjmedia_sdp_attr_create(pool, "ptime", pj_cstr(&stmp, tmp));
1329                 media->attr[media->attr_count++] = attr;
1330         }
1331
1332         if (max_packet_size) {
1333                 snprintf(tmp, sizeof(tmp), "%d", max_packet_size);
1334                 attr = pjmedia_sdp_attr_create(pool, "maxptime", pj_cstr(&stmp, tmp));
1335                 media->attr[media->attr_count++] = attr;
1336         }
1337
1338         /* Add the sendrecv attribute - we purposely don't keep track because pjmedia-sdp will automatically change our offer for us */
1339         attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr);
1340         attr->name = !session_media->locally_held ? STR_SENDRECV : STR_SENDONLY;
1341         media->attr[media->attr_count++] = attr;
1342
1343         /* If we've got rtcp-mux enabled, just unconditionally offer it in all SDPs */
1344         if (session->endpoint->media.rtcp_mux) {
1345                 attr = pjmedia_sdp_attr_create(pool, "rtcp-mux", NULL);
1346                 pjmedia_sdp_attr_add(&media->attr_count, media->attr, attr);
1347         }
1348
1349         /* Add the media stream to the SDP */
1350         sdp->media[sdp->media_count++] = media;
1351
1352         return 1;
1353 }
1354
1355 static int apply_negotiated_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
1356                                        const struct pjmedia_sdp_session *local, const struct pjmedia_sdp_media *local_stream,
1357                                        const struct pjmedia_sdp_session *remote, const struct pjmedia_sdp_media *remote_stream)
1358 {
1359         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
1360         enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
1361         char host[NI_MAXHOST];
1362         int fdno, res;
1363
1364         if (!session->channel) {
1365                 return 1;
1366         }
1367
1368         if (!local_stream->desc.port || !remote_stream->desc.port) {
1369                 return 1;
1370         }
1371
1372         /* Ensure incoming transport is compatible with the endpoint's configuration */
1373         if (!session->endpoint->media.rtp.use_received_transport &&
1374                 check_endpoint_media_transport(session->endpoint, remote_stream) == AST_SIP_MEDIA_TRANSPORT_INVALID) {
1375                 return -1;
1376         }
1377
1378         /* Create an RTP instance if need be */
1379         if (!session_media->rtp && create_rtp(session, session_media)) {
1380                 return -1;
1381         }
1382
1383         session_media->remote_rtcp_mux = (pjmedia_sdp_media_find_attr2(remote_stream, "rtcp-mux", NULL) != NULL);
1384         set_ice_components(session, session_media);
1385
1386         enable_rtcp(session, session_media, remote_stream);
1387
1388         res = setup_media_encryption(session, session_media, remote, remote_stream);
1389         if (!session->endpoint->media.rtp.encryption_optimistic && res) {
1390                 /* If optimistic encryption is disabled and crypto should have been enabled but was not
1391                  * this session must fail.
1392                  */
1393                 return -1;
1394         }
1395
1396         if (!remote_stream->conn && !remote->conn) {
1397                 return 1;
1398         }
1399
1400         ast_copy_pj_str(host, remote_stream->conn ? &remote_stream->conn->addr : &remote->conn->addr, sizeof(host));
1401
1402         /* Ensure that the address provided is valid */
1403         if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
1404                 /* The provided host was actually invalid so we error out this negotiation */
1405                 return -1;
1406         }
1407
1408         /* Apply connection information to the RTP instance */
1409         ast_sockaddr_set_port(addrs, remote_stream->desc.port);
1410         ast_rtp_instance_set_remote_address(session_media->rtp, addrs);
1411         if (set_caps(session, session_media, remote_stream, 0)) {
1412                 return 1;
1413         }
1414
1415         if ((fdno = media_type_to_fdno(media_type)) < 0) {
1416                 return -1;
1417         }
1418         ast_channel_set_fd(session->channel, fdno, ast_rtp_instance_fd(session_media->rtp, 0));
1419         if (!session->endpoint->media.rtcp_mux || !session_media->remote_rtcp_mux) {
1420                 ast_channel_set_fd(session->channel, fdno + 1, ast_rtp_instance_fd(session_media->rtp, 1));
1421         }
1422
1423         /* If ICE support is enabled find all the needed attributes */
1424         process_ice_attributes(session, session_media, remote, remote_stream);
1425
1426         /* Ensure the RTP instance is active */
1427         ast_rtp_instance_activate(session_media->rtp);
1428
1429         /* audio stream handles music on hold */
1430         if (media_type != AST_MEDIA_TYPE_AUDIO) {
1431                 if ((pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_FALSE)
1432                         && (session->inv_session->state == PJSIP_INV_STATE_CONFIRMED)) {
1433                         ast_queue_control(session->channel, AST_CONTROL_UPDATE_RTP_PEER);
1434                 }
1435                 return 1;
1436         }
1437
1438         if (ast_sockaddr_isnull(addrs) ||
1439                 ast_sockaddr_is_any(addrs) ||
1440                 pjmedia_sdp_media_find_attr2(remote_stream, "sendonly", NULL) ||
1441                 pjmedia_sdp_media_find_attr2(remote_stream, "inactive", NULL)) {
1442                 if (!session_media->remotely_held) {
1443                         /* The remote side has put us on hold */
1444                         ast_queue_hold(session->channel, session->endpoint->mohsuggest);
1445                         ast_rtp_instance_stop(session_media->rtp);
1446                         ast_queue_frame(session->channel, &ast_null_frame);
1447                         session_media->remotely_held = 1;
1448                 }
1449         } else if (session_media->remotely_held) {
1450                 /* The remote side has taken us off hold */
1451                 ast_queue_unhold(session->channel);
1452                 ast_queue_frame(session->channel, &ast_null_frame);
1453                 session_media->remotely_held = 0;
1454         } else if ((pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_FALSE)
1455                 && (session->inv_session->state == PJSIP_INV_STATE_CONFIRMED)) {
1456                 ast_queue_control(session->channel, AST_CONTROL_UPDATE_RTP_PEER);
1457         }
1458
1459         /* This purposely resets the encryption to the configured in case it gets added later */
1460         session_media->encryption = session->endpoint->media.rtp.encryption;
1461
1462         if (session->endpoint->media.rtp.keepalive > 0 &&
1463                         stream_to_media_type(session_media->stream_type) == AST_MEDIA_TYPE_AUDIO) {
1464                 ast_rtp_instance_set_keepalive(session_media->rtp, session->endpoint->media.rtp.keepalive);
1465                 /* Schedule the initial keepalive early in case this is being used to punch holes through
1466                  * a NAT. This way there won't be an awkward delay before media starts flowing in some
1467                  * scenarios.
1468                  */
1469                 AST_SCHED_DEL(sched, session_media->keepalive_sched_id);
1470                 session_media->keepalive_sched_id = ast_sched_add_variable(sched, 500, send_keepalive,
1471                         session_media, 1);
1472         }
1473
1474         /* As the channel lock is not held during this process the scheduled item won't block if
1475          * it is hanging up the channel at the same point we are applying this negotiated SDP.
1476          */
1477         AST_SCHED_DEL(sched, session_media->timeout_sched_id);
1478
1479         /* Due to the fact that we only ever have one scheduled timeout item for when we are both
1480          * off hold and on hold we don't need to store the two timeouts differently on the RTP
1481          * instance itself.
1482          */
1483         ast_rtp_instance_set_timeout(session_media->rtp, 0);
1484         if (session->endpoint->media.rtp.timeout && !session_media->remotely_held) {
1485                 ast_rtp_instance_set_timeout(session_media->rtp, session->endpoint->media.rtp.timeout);
1486         } else if (session->endpoint->media.rtp.timeout_hold && session_media->remotely_held) {
1487                 ast_rtp_instance_set_timeout(session_media->rtp, session->endpoint->media.rtp.timeout_hold);
1488         }
1489
1490         if (ast_rtp_instance_get_timeout(session_media->rtp)) {
1491                 session_media->timeout_sched_id = ast_sched_add_variable(sched,
1492                         ast_rtp_instance_get_timeout(session_media->rtp) * 1000, rtp_check_timeout,
1493                         session_media, 1);
1494         }
1495
1496         return 1;
1497 }
1498
1499 /*! \brief Function which updates the media stream with external media address, if applicable */
1500 static void change_outgoing_sdp_stream_media_address(pjsip_tx_data *tdata, struct pjmedia_sdp_media *stream, struct ast_sip_transport *transport)
1501 {
1502         RAII_VAR(struct ast_sip_transport_state *, transport_state, ast_sip_get_transport_state(ast_sorcery_object_get_id(transport)), ao2_cleanup);
1503         char host[NI_MAXHOST];
1504         struct ast_sockaddr addr = { { 0, } };
1505
1506         /* If the stream has been rejected there will be no connection line */
1507         if (!stream->conn || !transport_state) {
1508                 return;
1509         }
1510
1511         ast_copy_pj_str(host, &stream->conn->addr, sizeof(host));
1512         ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID);
1513
1514         /* Is the address within the SDP inside the same network? */
1515         if (transport_state->localnet
1516                 && ast_apply_ha(transport_state->localnet, &addr) == AST_SENSE_ALLOW) {
1517                 return;
1518         }
1519         ast_debug(5, "Setting media address to %s\n", transport->external_media_address);
1520         pj_strdup2(tdata->pool, &stream->conn->addr, transport->external_media_address);
1521 }
1522
1523 /*! \brief Function which stops the RTP instance */
1524 static void stream_stop(struct ast_sip_session_media *session_media)
1525 {
1526         if (!session_media->rtp) {
1527                 return;
1528         }
1529
1530         AST_SCHED_DEL(sched, session_media->keepalive_sched_id);
1531         AST_SCHED_DEL(sched, session_media->timeout_sched_id);
1532         ast_rtp_instance_stop(session_media->rtp);
1533 }
1534
1535 /*! \brief Function which destroys the RTP instance when session ends */
1536 static void stream_destroy(struct ast_sip_session_media *session_media)
1537 {
1538         if (session_media->rtp) {
1539                 stream_stop(session_media);
1540                 ast_rtp_instance_destroy(session_media->rtp);
1541         }
1542         session_media->rtp = NULL;
1543 }
1544
1545 /*! \brief SDP handler for 'audio' media stream */
1546 static struct ast_sip_session_sdp_handler audio_sdp_handler = {
1547         .id = STR_AUDIO,
1548         .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
1549         .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
1550         .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
1551         .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
1552         .stream_stop = stream_stop,
1553         .stream_destroy = stream_destroy,
1554 };
1555
1556 /*! \brief SDP handler for 'video' media stream */
1557 static struct ast_sip_session_sdp_handler video_sdp_handler = {
1558         .id = STR_VIDEO,
1559         .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
1560         .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
1561         .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
1562         .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
1563         .stream_stop = stream_stop,
1564         .stream_destroy = stream_destroy,
1565 };
1566
1567 static int video_info_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
1568 {
1569         struct pjsip_transaction *tsx;
1570         pjsip_tx_data *tdata;
1571
1572         if (!session->channel
1573                 || !ast_sip_is_content_type(&rdata->msg_info.msg->body->content_type,
1574                         "application",
1575                         "media_control+xml")) {
1576                 return 0;
1577         }
1578
1579         tsx = pjsip_rdata_get_tsx(rdata);
1580
1581         ast_queue_control(session->channel, AST_CONTROL_VIDUPDATE);
1582
1583         if (pjsip_dlg_create_response(session->inv_session->dlg, rdata, 200, NULL, &tdata) == PJ_SUCCESS) {
1584                 pjsip_dlg_send_response(session->inv_session->dlg, tsx, tdata);
1585         }
1586
1587         return 0;
1588 }
1589
1590 static struct ast_sip_session_supplement video_info_supplement = {
1591         .method = "INFO",
1592         .incoming_request = video_info_incoming_request,
1593 };
1594
1595 /*! \brief Unloads the sdp RTP/AVP module from Asterisk */
1596 static int unload_module(void)
1597 {
1598         ast_sip_session_unregister_supplement(&video_info_supplement);
1599         ast_sip_session_unregister_sdp_handler(&video_sdp_handler, STR_VIDEO);
1600         ast_sip_session_unregister_sdp_handler(&audio_sdp_handler, STR_AUDIO);
1601
1602         if (sched) {
1603                 ast_sched_context_destroy(sched);
1604         }
1605
1606         return 0;
1607 }
1608
1609 /*!
1610  * \brief Load the module
1611  *
1612  * Module loading including tests for configuration or dependencies.
1613  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1614  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1615  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
1616  * configuration file or other non-critical problem return
1617  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1618  */
1619 static int load_module(void)
1620 {
1621         CHECK_PJSIP_SESSION_MODULE_LOADED();
1622
1623         if (ast_check_ipv6()) {
1624                 ast_sockaddr_parse(&address_rtp, "::", 0);
1625         } else {
1626                 ast_sockaddr_parse(&address_rtp, "0.0.0.0", 0);
1627         }
1628
1629         if (!(sched = ast_sched_context_create())) {
1630                 ast_log(LOG_ERROR, "Unable to create scheduler context.\n");
1631                 goto end;
1632         }
1633
1634         if (ast_sched_start_thread(sched)) {
1635                 ast_log(LOG_ERROR, "Unable to create scheduler context thread.\n");
1636                 goto end;
1637         }
1638
1639         if (ast_sip_session_register_sdp_handler(&audio_sdp_handler, STR_AUDIO)) {
1640                 ast_log(LOG_ERROR, "Unable to register SDP handler for %s stream type\n", STR_AUDIO);
1641                 goto end;
1642         }
1643
1644         if (ast_sip_session_register_sdp_handler(&video_sdp_handler, STR_VIDEO)) {
1645                 ast_log(LOG_ERROR, "Unable to register SDP handler for %s stream type\n", STR_VIDEO);
1646                 goto end;
1647         }
1648
1649         ast_sip_session_register_supplement(&video_info_supplement);
1650
1651         return AST_MODULE_LOAD_SUCCESS;
1652 end:
1653         unload_module();
1654
1655         return AST_MODULE_LOAD_DECLINE;
1656 }
1657
1658 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP SDP RTP/AVP stream handler",
1659         .support_level = AST_MODULE_SUPPORT_CORE,
1660         .load = load_module,
1661         .unload = unload_module,
1662         .load_pri = AST_MODPRI_CHANNEL_DRIVER,
1663 );