res_pjsip_sdp_rtp,sorcery: Fix invalid access and memory leak respectively.
[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 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
42
43 #include "asterisk/module.h"
44 #include "asterisk/format.h"
45 #include "asterisk/format_cap.h"
46 #include "asterisk/rtp_engine.h"
47 #include "asterisk/netsock2.h"
48 #include "asterisk/channel.h"
49 #include "asterisk/causes.h"
50 #include "asterisk/sched.h"
51 #include "asterisk/acl.h"
52 #include "asterisk/sdp_srtp.h"
53
54 #include "asterisk/res_pjsip.h"
55 #include "asterisk/res_pjsip_session.h"
56
57 /*! \brief Scheduler for RTCP purposes */
58 static struct ast_sched_context *sched;
59
60 /*! \brief Address for IPv4 RTP */
61 static struct ast_sockaddr address_ipv4;
62
63 /*! \brief Address for IPv6 RTP */
64 static struct ast_sockaddr address_ipv6;
65
66 static const char STR_AUDIO[] = "audio";
67 static const int FD_AUDIO = 0;
68
69 static const char STR_VIDEO[] = "video";
70 static const int FD_VIDEO = 2;
71
72 /*! \brief Retrieves an ast_format_type based on the given stream_type */
73 static enum ast_media_type stream_to_media_type(const char *stream_type)
74 {
75         if (!strcasecmp(stream_type, STR_AUDIO)) {
76                 return AST_MEDIA_TYPE_AUDIO;
77         } else if (!strcasecmp(stream_type, STR_VIDEO)) {
78                 return AST_MEDIA_TYPE_VIDEO;
79         }
80
81         return 0;
82 }
83
84 /*! \brief Get the starting descriptor for a media type */
85 static int media_type_to_fdno(enum ast_media_type media_type)
86 {
87         switch (media_type) {
88         case AST_MEDIA_TYPE_AUDIO: return FD_AUDIO;
89         case AST_MEDIA_TYPE_VIDEO: return FD_VIDEO;
90         case AST_MEDIA_TYPE_TEXT:
91         case AST_MEDIA_TYPE_UNKNOWN:
92         case AST_MEDIA_TYPE_IMAGE: break;
93         }
94         return -1;
95 }
96
97 /*! \brief Remove all other cap types but the one given */
98 static void format_cap_only_type(struct ast_format_cap *caps, enum ast_media_type media_type)
99 {
100         int i = 0;
101         while (i <= AST_MEDIA_TYPE_TEXT) {
102                 if (i != media_type && i != AST_MEDIA_TYPE_UNKNOWN) {
103                         ast_format_cap_remove_by_type(caps, i);
104                 }
105                 i += 1;
106         }
107 }
108
109 /*! \brief Internal function which creates an RTP instance */
110 static int create_rtp(struct ast_sip_session *session, struct ast_sip_session_media *session_media, unsigned int ipv6)
111 {
112         struct ast_rtp_engine_ice *ice;
113
114         if (!(session_media->rtp = ast_rtp_instance_new(session->endpoint->media.rtp.engine, sched, ipv6 ? &address_ipv6 : &address_ipv4, NULL))) {
115                 ast_log(LOG_ERROR, "Unable to create RTP instance using RTP engine '%s'\n", session->endpoint->media.rtp.engine);
116                 return -1;
117         }
118
119         ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_RTCP, 1);
120         ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_NAT, session->endpoint->media.rtp.symmetric);
121
122         if (!session->endpoint->media.rtp.ice_support && (ice = ast_rtp_instance_get_ice(session_media->rtp))) {
123                 ice->stop(session_media->rtp);
124         }
125
126         if (session->endpoint->dtmf == AST_SIP_DTMF_RFC_4733) {
127                 ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_RFC2833);
128                 ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_DTMF, 1);
129         } else if (session->endpoint->dtmf == AST_SIP_DTMF_INBAND) {
130                 ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_INBAND);
131         }
132
133         if (!strcmp(session_media->stream_type, STR_AUDIO) &&
134                         (session->endpoint->media.tos_audio || session->endpoint->media.cos_video)) {
135                 ast_rtp_instance_set_qos(session_media->rtp, session->endpoint->media.tos_audio,
136                                 session->endpoint->media.cos_audio, "SIP RTP Audio");
137         } else if (!strcmp(session_media->stream_type, STR_VIDEO) &&
138                         (session->endpoint->media.tos_video || session->endpoint->media.cos_video)) {
139                 ast_rtp_instance_set_qos(session_media->rtp, session->endpoint->media.tos_video,
140                                 session->endpoint->media.cos_video, "SIP RTP Video");
141         }
142
143         return 0;
144 }
145
146 static void get_codecs(struct ast_sip_session *session, const struct pjmedia_sdp_media *stream, struct ast_rtp_codecs *codecs)
147 {
148         pjmedia_sdp_attr *attr;
149         pjmedia_sdp_rtpmap *rtpmap;
150         pjmedia_sdp_fmtp fmtp;
151         struct ast_format *format;
152         int i, num = 0;
153         char name[256];
154         char media[20];
155         char fmt_param[256];
156
157         ast_rtp_codecs_payloads_initialize(codecs);
158
159         /* Iterate through provided formats */
160         for (i = 0; i < stream->desc.fmt_count; ++i) {
161                 /* The payload is kept as a string for things like t38 but for video it is always numerical */
162                 ast_rtp_codecs_payloads_set_m_type(codecs, NULL, pj_strtoul(&stream->desc.fmt[i]));
163                 /* Look for the optional rtpmap attribute */
164                 if (!(attr = pjmedia_sdp_media_find_attr2(stream, "rtpmap", &stream->desc.fmt[i]))) {
165                         continue;
166                 }
167
168                 /* Interpret the attribute as an rtpmap */
169                 if ((pjmedia_sdp_attr_to_rtpmap(session->inv_session->pool_prov, attr, &rtpmap)) != PJ_SUCCESS) {
170                         continue;
171                 }
172
173                 ast_copy_pj_str(name, &rtpmap->enc_name, sizeof(name));
174                 ast_copy_pj_str(media, (pj_str_t*)&stream->desc.media, sizeof(media));
175                 ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, NULL, pj_strtoul(&stream->desc.fmt[i]),
176                                                              media, name, 0, rtpmap->clock_rate);
177                 /* Look for an optional associated fmtp attribute */
178                 if (!(attr = pjmedia_sdp_media_find_attr2(stream, "fmtp", &rtpmap->pt))) {
179                         continue;
180                 }
181
182                 if ((pjmedia_sdp_attr_get_fmtp(attr, &fmtp)) == PJ_SUCCESS) {
183                         ast_copy_pj_str(fmt_param, &fmtp.fmt, sizeof(fmt_param));
184                         if (sscanf(fmt_param, "%30d", &num) != 1) {
185                                 continue;
186                         }
187
188                         if ((format = ast_rtp_codecs_get_payload_format(codecs, num))) {
189                                 struct ast_format *format_parsed;
190
191                                 ast_copy_pj_str(fmt_param, &fmtp.fmt_param, sizeof(fmt_param));
192
193                                 format_parsed = ast_format_parse_sdp_fmtp(format, fmt_param);
194                                 if (format_parsed) {
195                                         ast_rtp_codecs_payload_replace_format(codecs, num, format_parsed);
196                                         ao2_ref(format_parsed, -1);
197                                 }
198
199                                 ao2_ref(format, -1);
200                         }
201                 }
202         }
203
204         /* Get the packetization, if it exists */
205         if ((attr = pjmedia_sdp_media_find_attr2(stream, "ptime", NULL))) {
206                 unsigned long framing = pj_strtoul(pj_strltrim(&attr->value));
207                 if (framing && session->endpoint->media.rtp.use_ptime) {
208                         ast_rtp_codecs_set_framing(codecs, framing);
209                 }
210         }
211 }
212
213 static int set_caps(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
214                     const struct pjmedia_sdp_media *stream)
215 {
216         RAII_VAR(struct ast_format_cap *, caps, NULL, ao2_cleanup);
217         RAII_VAR(struct ast_format_cap *, peer, NULL, ao2_cleanup);
218         RAII_VAR(struct ast_format_cap *, joint, NULL, ao2_cleanup);
219         enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
220         struct ast_rtp_codecs codecs = AST_RTP_CODECS_NULL_INIT;
221         int fmts = 0;
222         int direct_media_enabled = !ast_sockaddr_isnull(&session_media->direct_media_addr) &&
223                 ast_format_cap_count(session->direct_media_cap);
224
225         if (!(caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT)) ||
226             !(peer = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT)) ||
227             !(joint = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
228                 ast_log(LOG_ERROR, "Failed to allocate %s capabilities\n", session_media->stream_type);
229                 return -1;
230         }
231
232         /* get the endpoint capabilities */
233         if (direct_media_enabled) {
234                 ast_format_cap_get_compatible(session->endpoint->media.codecs, session->direct_media_cap, caps);
235                 format_cap_only_type(caps, media_type);
236         } else {
237                 ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, media_type);
238         }
239
240         /* get the capabilities on the peer */
241         get_codecs(session, stream, &codecs);
242         ast_rtp_codecs_payload_formats(&codecs, peer, &fmts);
243
244         /* get the joint capabilities between peer and endpoint */
245         ast_format_cap_get_compatible(caps, peer, joint);
246         if (!ast_format_cap_count(joint)) {
247                 struct ast_str *usbuf = ast_str_alloca(64);
248                 struct ast_str *thembuf = ast_str_alloca(64);
249
250                 ast_rtp_codecs_payloads_destroy(&codecs);
251                 ast_log(LOG_NOTICE, "No joint capabilities for '%s' media stream between our configuration(%s) and incoming SDP(%s)\n",
252                         session_media->stream_type,
253                         ast_format_cap_get_names(caps, &usbuf),
254                         ast_format_cap_get_names(peer, &thembuf));
255                 return -1;
256         }
257
258         ast_rtp_codecs_payloads_copy(&codecs, ast_rtp_instance_get_codecs(session_media->rtp),
259                                      session_media->rtp);
260
261         ast_format_cap_append_from_cap(session->req_caps, joint, AST_MEDIA_TYPE_UNKNOWN);
262
263         if (session->channel) {
264                 struct ast_format *fmt;
265
266                 ast_channel_lock(session->channel);
267                 ast_format_cap_remove_by_type(caps, AST_MEDIA_TYPE_UNKNOWN);
268                 ast_format_cap_append_from_cap(caps, ast_channel_nativeformats(session->channel), AST_MEDIA_TYPE_UNKNOWN);
269                 ast_format_cap_remove_by_type(caps, media_type);
270
271                 /*
272                  * XXX Historically we picked the "best" joint format to use
273                  * and stuck with it.  It would be nice to just append the
274                  * determined joint media capabilities to give translation
275                  * more formats to choose from when necessary.  Unfortunately,
276                  * there are some areas of the system where this doesn't work
277                  * very well. (The softmix bridge in particular is reluctant
278                  * to pick higher fidelity formats and has a problem with
279                  * asymmetric sample rates.)
280                  */
281                 fmt = ast_format_cap_get_format(joint, 0);
282                 ast_format_cap_append(caps, fmt, 0);
283
284                 /*
285                  * Apply the new formats to the channel, potentially changing
286                  * raw read/write formats and translation path while doing so.
287                  */
288                 ast_channel_nativeformats_set(session->channel, caps);
289                 ast_set_read_format(session->channel, ast_channel_readformat(session->channel));
290                 ast_set_write_format(session->channel, ast_channel_writeformat(session->channel));
291                 ast_channel_unlock(session->channel);
292
293                 ao2_ref(fmt, -1);
294         }
295
296         ast_rtp_codecs_payloads_destroy(&codecs);
297         return 0;
298 }
299
300 static pjmedia_sdp_attr* generate_rtpmap_attr(pjmedia_sdp_media *media, pj_pool_t *pool, int rtp_code,
301                                               int asterisk_format, struct ast_format *format, int code)
302 {
303         pjmedia_sdp_rtpmap rtpmap;
304         pjmedia_sdp_attr *attr = NULL;
305         char tmp[64];
306
307         snprintf(tmp, sizeof(tmp), "%d", rtp_code);
308         pj_strdup2(pool, &media->desc.fmt[media->desc.fmt_count++], tmp);
309         rtpmap.pt = media->desc.fmt[media->desc.fmt_count - 1];
310         rtpmap.clock_rate = ast_rtp_lookup_sample_rate2(asterisk_format, format, code);
311         pj_strdup2(pool, &rtpmap.enc_name, ast_rtp_lookup_mime_subtype2(asterisk_format, format, code, 0));
312         rtpmap.param.slen = 0;
313         rtpmap.param.ptr = NULL;
314
315         pjmedia_sdp_rtpmap_to_attr(pool, &rtpmap, &attr);
316
317         return attr;
318 }
319
320 static pjmedia_sdp_attr* generate_fmtp_attr(pj_pool_t *pool, struct ast_format *format, int rtp_code)
321 {
322         struct ast_str *fmtp0 = ast_str_alloca(256);
323         pj_str_t fmtp1;
324         pjmedia_sdp_attr *attr = NULL;
325         char *tmp;
326
327         ast_format_generate_sdp_fmtp(format, rtp_code, &fmtp0);
328         if (ast_str_strlen(fmtp0)) {
329                 tmp = ast_str_buffer(fmtp0) + ast_str_strlen(fmtp0) - 1;
330                 /* remove any carriage return line feeds */
331                 while (*tmp == '\r' || *tmp == '\n') --tmp;
332                 *++tmp = '\0';
333                 /* ast...generate gives us everything, just need value */
334                 tmp = strchr(ast_str_buffer(fmtp0), ':');
335                 if (tmp && tmp + 1) {
336                         fmtp1 = pj_str(tmp + 1);
337                 } else {
338                         fmtp1 = pj_str(ast_str_buffer(fmtp0));
339                 }
340                 attr = pjmedia_sdp_attr_create(pool, "fmtp", &fmtp1);
341         }
342         return attr;
343 }
344
345 /*! \brief Function which adds ICE attributes to a media stream */
346 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)
347 {
348         struct ast_rtp_engine_ice *ice;
349         struct ao2_container *candidates;
350         const char *username, *password;
351         pj_str_t stmp;
352         pjmedia_sdp_attr *attr;
353         struct ao2_iterator it_candidates;
354         struct ast_rtp_engine_ice_candidate *candidate;
355
356         if (!session->endpoint->media.rtp.ice_support || !(ice = ast_rtp_instance_get_ice(session_media->rtp)) ||
357                 !(candidates = ice->get_local_candidates(session_media->rtp))) {
358                 return;
359         }
360
361         if ((username = ice->get_ufrag(session_media->rtp))) {
362                 attr = pjmedia_sdp_attr_create(pool, "ice-ufrag", pj_cstr(&stmp, username));
363                 media->attr[media->attr_count++] = attr;
364         }
365
366         if ((password = ice->get_password(session_media->rtp))) {
367                 attr = pjmedia_sdp_attr_create(pool, "ice-pwd", pj_cstr(&stmp, password));
368                 media->attr[media->attr_count++] = attr;
369         }
370
371         it_candidates = ao2_iterator_init(candidates, 0);
372         for (; (candidate = ao2_iterator_next(&it_candidates)); ao2_ref(candidate, -1)) {
373                 struct ast_str *attr_candidate = ast_str_create(128);
374
375                 ast_str_set(&attr_candidate, -1, "%s %u %s %d %s ", candidate->foundation, candidate->id, candidate->transport,
376                                         candidate->priority, ast_sockaddr_stringify_addr_remote(&candidate->address));
377                 ast_str_append(&attr_candidate, -1, "%s typ ", ast_sockaddr_stringify_port(&candidate->address));
378
379                 switch (candidate->type) {
380                         case AST_RTP_ICE_CANDIDATE_TYPE_HOST:
381                                 ast_str_append(&attr_candidate, -1, "host");
382                                 break;
383                         case AST_RTP_ICE_CANDIDATE_TYPE_SRFLX:
384                                 ast_str_append(&attr_candidate, -1, "srflx");
385                                 break;
386                         case AST_RTP_ICE_CANDIDATE_TYPE_RELAYED:
387                                 ast_str_append(&attr_candidate, -1, "relay");
388                                 break;
389                 }
390
391                 if (!ast_sockaddr_isnull(&candidate->relay_address)) {
392                         ast_str_append(&attr_candidate, -1, " raddr %s rport", ast_sockaddr_stringify_addr_remote(&candidate->relay_address));
393                         ast_str_append(&attr_candidate, -1, " %s", ast_sockaddr_stringify_port(&candidate->relay_address));
394                 }
395
396                 attr = pjmedia_sdp_attr_create(pool, "candidate", pj_cstr(&stmp, ast_str_buffer(attr_candidate)));
397                 media->attr[media->attr_count++] = attr;
398
399                 ast_free(attr_candidate);
400         }
401
402         ao2_iterator_destroy(&it_candidates);
403         ao2_ref(candidates, -1);
404 }
405
406 /*! \brief Function which processes ICE attributes in an audio stream */
407 static void process_ice_attributes(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
408                                    const struct pjmedia_sdp_session *remote, const struct pjmedia_sdp_media *remote_stream)
409 {
410         struct ast_rtp_engine_ice *ice;
411         const pjmedia_sdp_attr *attr;
412         char attr_value[256];
413         unsigned int attr_i;
414
415         /* If ICE support is not enabled or available exit early */
416         if (!session->endpoint->media.rtp.ice_support || !(ice = ast_rtp_instance_get_ice(session_media->rtp))) {
417                 return;
418         }
419
420         attr = pjmedia_sdp_media_find_attr2(remote_stream, "ice-ufrag", NULL);
421         if (!attr) {
422                 attr = pjmedia_sdp_attr_find2(remote->attr_count, remote->attr, "ice-ufrag", NULL);
423         }
424         if (attr) {
425                 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
426                 ice->set_authentication(session_media->rtp, attr_value, NULL);
427         } else {
428                 return;
429         }
430
431         attr = pjmedia_sdp_media_find_attr2(remote_stream, "ice-pwd", NULL);
432         if (!attr) {
433                 attr = pjmedia_sdp_attr_find2(remote->attr_count, remote->attr, "ice-pwd", NULL);
434         }
435         if (attr) {
436                 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
437                 ice->set_authentication(session_media->rtp, NULL, attr_value);
438         } else {
439                 return;
440         }
441
442         if (pjmedia_sdp_media_find_attr2(remote_stream, "ice-lite", NULL)) {
443                 ice->ice_lite(session_media->rtp);
444         }
445
446         /* Find all of the candidates */
447         for (attr_i = 0; attr_i < remote_stream->attr_count; ++attr_i) {
448                 char foundation[32], transport[32], address[PJ_INET6_ADDRSTRLEN + 1], cand_type[6], relay_address[PJ_INET6_ADDRSTRLEN + 1] = "";
449                 unsigned int port, relay_port = 0;
450                 struct ast_rtp_engine_ice_candidate candidate = { 0, };
451
452                 attr = remote_stream->attr[attr_i];
453
454                 /* If this is not a candidate line skip it */
455                 if (pj_strcmp2(&attr->name, "candidate")) {
456                         continue;
457                 }
458
459                 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
460
461                 if (sscanf(attr_value, "%31s %30u %31s %30u %46s %30u typ %5s %*s %23s %*s %30u", foundation, &candidate.id, transport,
462                         (unsigned *)&candidate.priority, address, &port, cand_type, relay_address, &relay_port) < 7) {
463                         /* Candidate did not parse properly */
464                         continue;
465                 }
466
467                 candidate.foundation = foundation;
468                 candidate.transport = transport;
469
470                 ast_sockaddr_parse(&candidate.address, address, PARSE_PORT_FORBID);
471                 ast_sockaddr_set_port(&candidate.address, port);
472
473                 if (!strcasecmp(cand_type, "host")) {
474                         candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
475                 } else if (!strcasecmp(cand_type, "srflx")) {
476                         candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
477                 } else if (!strcasecmp(cand_type, "relay")) {
478                         candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
479                 } else {
480                         continue;
481                 }
482
483                 if (!ast_strlen_zero(relay_address)) {
484                         ast_sockaddr_parse(&candidate.relay_address, relay_address, PARSE_PORT_FORBID);
485                 }
486
487                 if (relay_port) {
488                         ast_sockaddr_set_port(&candidate.relay_address, relay_port);
489                 }
490
491                 ice->add_remote_candidate(session_media->rtp, &candidate);
492         }
493
494         ice->set_role(session_media->rtp, pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_TRUE ?
495                 AST_RTP_ICE_ROLE_CONTROLLING : AST_RTP_ICE_ROLE_CONTROLLED);
496         ice->start(session_media->rtp);
497 }
498
499 /*! \brief figure out if media stream has crypto lines for sdes */
500 static int media_stream_has_crypto(const struct pjmedia_sdp_media *stream)
501 {
502         int i;
503
504         for (i = 0; i < stream->attr_count; i++) {
505                 pjmedia_sdp_attr *attr;
506
507                 /* check the stream for the required crypto attribute */
508                 attr = stream->attr[i];
509                 if (pj_strcmp2(&attr->name, "crypto")) {
510                         continue;
511                 }
512
513                 return 1;
514         }
515
516         return 0;
517 }
518
519 /*! \brief figure out media transport encryption type from the media transport string */
520 static enum ast_sip_session_media_encryption get_media_encryption_type(pj_str_t transport,
521         const struct pjmedia_sdp_media *stream, unsigned int *optimistic)
522 {
523         RAII_VAR(char *, transport_str, ast_strndup(transport.ptr, transport.slen), ast_free);
524
525         *optimistic = 0;
526
527         if (strstr(transport_str, "UDP/TLS")) {
528                 return AST_SIP_MEDIA_ENCRYPT_DTLS;
529         } else if (strstr(transport_str, "SAVP")) {
530                 return AST_SIP_MEDIA_ENCRYPT_SDES;
531         } else if (media_stream_has_crypto(stream)) {
532                 *optimistic = 1;
533                 return AST_SIP_MEDIA_ENCRYPT_SDES;
534         } else {
535                 return AST_SIP_MEDIA_ENCRYPT_NONE;
536         }
537 }
538
539 /*!
540  * \brief Checks whether the encryption offered in SDP is compatible with the endpoint's configuration
541  * \internal
542  *
543  * \param endpoint_encryption Media encryption configured for the endpoint
544  * \param stream pjmedia_sdp_media stream description
545  *
546  * \retval AST_SIP_MEDIA_TRANSPORT_INVALID on encryption mismatch
547  * \retval The encryption requested in the SDP
548  */
549 static enum ast_sip_session_media_encryption check_endpoint_media_transport(
550         struct ast_sip_endpoint *endpoint,
551         const struct pjmedia_sdp_media *stream)
552 {
553         enum ast_sip_session_media_encryption incoming_encryption;
554         char transport_end = stream->desc.transport.ptr[stream->desc.transport.slen - 1];
555         unsigned int optimistic;
556
557         if ((transport_end == 'F' && !endpoint->media.rtp.use_avpf)
558                 || (transport_end != 'F' && endpoint->media.rtp.use_avpf)) {
559                 return AST_SIP_MEDIA_TRANSPORT_INVALID;
560         }
561
562         incoming_encryption = get_media_encryption_type(stream->desc.transport, stream, &optimistic);
563
564         if (incoming_encryption == endpoint->media.rtp.encryption) {
565                 return incoming_encryption;
566         }
567
568         if (endpoint->media.rtp.force_avp ||
569                 endpoint->media.rtp.encryption_optimistic) {
570                 return incoming_encryption;
571         }
572
573         /* If an optimistic offer has been made but encryption is not enabled consider it as having
574          * no offer of crypto at all instead of invalid so the session proceeds.
575          */
576         if (optimistic) {
577                 return AST_SIP_MEDIA_ENCRYPT_NONE;
578         }
579
580         return AST_SIP_MEDIA_TRANSPORT_INVALID;
581 }
582
583 static int setup_srtp(struct ast_sip_session_media *session_media)
584 {
585         if (!session_media->srtp) {
586                 session_media->srtp = ast_sdp_srtp_alloc();
587                 if (!session_media->srtp) {
588                         return -1;
589                 }
590         }
591
592         if (!session_media->srtp->crypto) {
593                 session_media->srtp->crypto = ast_sdp_crypto_alloc();
594                 if (!session_media->srtp->crypto) {
595                         return -1;
596                 }
597         }
598
599         return 0;
600 }
601
602 static int setup_dtls_srtp(struct ast_sip_session *session,
603         struct ast_sip_session_media *session_media)
604 {
605         struct ast_rtp_engine_dtls *dtls;
606
607         if (!session->endpoint->media.rtp.dtls_cfg.enabled || !session_media->rtp) {
608                 return -1;
609         }
610
611         dtls = ast_rtp_instance_get_dtls(session_media->rtp);
612         if (!dtls) {
613                 return -1;
614         }
615
616         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);
617         if (dtls->set_configuration(session_media->rtp, &session->endpoint->media.rtp.dtls_cfg)) {
618                 ast_log(LOG_ERROR, "Attempted to set an invalid DTLS-SRTP configuration on RTP instance '%p'\n",
619                         session_media->rtp);
620                 return -1;
621         }
622
623         if (setup_srtp(session_media)) {
624                 return -1;
625         }
626         return 0;
627 }
628
629 static void apply_dtls_attrib(struct ast_sip_session_media *session_media,
630         pjmedia_sdp_attr *attr)
631 {
632         struct ast_rtp_engine_dtls *dtls = ast_rtp_instance_get_dtls(session_media->rtp);
633         pj_str_t *value;
634
635         if (!attr->value.ptr) {
636                 return;
637         }
638
639         value = pj_strtrim(&attr->value);
640
641         if (!pj_strcmp2(&attr->name, "setup")) {
642                 if (!pj_stricmp2(value, "active")) {
643                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_ACTIVE);
644                 } else if (!pj_stricmp2(value, "passive")) {
645                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_PASSIVE);
646                 } else if (!pj_stricmp2(value, "actpass")) {
647                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_ACTPASS);
648                 } else if (!pj_stricmp2(value, "holdconn")) {
649                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_HOLDCONN);
650                 } else {
651                         ast_log(LOG_WARNING, "Unsupported setup attribute value '%*s'\n", (int)value->slen, value->ptr);
652                 }
653         } else if (!pj_strcmp2(&attr->name, "connection")) {
654                 if (!pj_stricmp2(value, "new")) {
655                         dtls->reset(session_media->rtp);
656                 } else if (!pj_stricmp2(value, "existing")) {
657                         /* Do nothing */
658                 } else {
659                         ast_log(LOG_WARNING, "Unsupported connection attribute value '%*s'\n", (int)value->slen, value->ptr);
660                 }
661         } else if (!pj_strcmp2(&attr->name, "fingerprint")) {
662                 char hash_value[256], hash[32];
663                 char fingerprint_text[value->slen + 1];
664                 ast_copy_pj_str(fingerprint_text, value, sizeof(fingerprint_text));
665                         if (sscanf(fingerprint_text, "%31s %255s", hash, hash_value) == 2) {
666                         if (!strcasecmp(hash, "sha-1")) {
667                                 dtls->set_fingerprint(session_media->rtp, AST_RTP_DTLS_HASH_SHA1, hash_value);
668                         } else if (!strcasecmp(hash, "sha-256")) {
669                                 dtls->set_fingerprint(session_media->rtp, AST_RTP_DTLS_HASH_SHA256, hash_value);
670                         } else {
671                                 ast_log(LOG_WARNING, "Unsupported fingerprint hash type '%s'\n",
672                                 hash);
673                         }
674                 }
675         }
676 }
677
678 static int parse_dtls_attrib(struct ast_sip_session_media *session_media,
679         const struct pjmedia_sdp_session *sdp,
680         const struct pjmedia_sdp_media *stream)
681 {
682         int i;
683
684         for (i = 0; i < sdp->attr_count; i++) {
685                 apply_dtls_attrib(session_media, sdp->attr[i]);
686         }
687
688         for (i = 0; i < stream->attr_count; i++) {
689                 apply_dtls_attrib(session_media, stream->attr[i]);
690         }
691
692         ast_set_flag(session_media->srtp, AST_SRTP_CRYPTO_OFFER_OK);
693
694         return 0;
695 }
696
697 static int setup_sdes_srtp(struct ast_sip_session_media *session_media,
698         const struct pjmedia_sdp_media *stream)
699 {
700         int i;
701
702         for (i = 0; i < stream->attr_count; i++) {
703                 pjmedia_sdp_attr *attr;
704                 RAII_VAR(char *, crypto_str, NULL, ast_free);
705
706                 /* check the stream for the required crypto attribute */
707                 attr = stream->attr[i];
708                 if (pj_strcmp2(&attr->name, "crypto")) {
709                         continue;
710                 }
711
712                 crypto_str = ast_strndup(attr->value.ptr, attr->value.slen);
713                 if (!crypto_str) {
714                         return -1;
715                 }
716
717                 if (setup_srtp(session_media)) {
718                         return -1;
719                 }
720
721                 if (!ast_sdp_crypto_process(session_media->rtp, session_media->srtp, crypto_str)) {
722                         /* found a valid crypto attribute */
723                         return 0;
724                 }
725
726                 ast_debug(1, "Ignoring crypto offer with unsupported parameters: %s\n", crypto_str);
727         }
728
729         /* no usable crypto attributes found */
730         return -1;
731 }
732
733 static int setup_media_encryption(struct ast_sip_session *session,
734         struct ast_sip_session_media *session_media,
735         const struct pjmedia_sdp_session *sdp,
736         const struct pjmedia_sdp_media *stream)
737 {
738         switch (session_media->encryption) {
739         case AST_SIP_MEDIA_ENCRYPT_SDES:
740                 if (setup_sdes_srtp(session_media, stream)) {
741                         return -1;
742                 }
743                 break;
744         case AST_SIP_MEDIA_ENCRYPT_DTLS:
745                 if (setup_dtls_srtp(session, session_media)) {
746                         return -1;
747                 }
748                 if (parse_dtls_attrib(session_media, sdp, stream)) {
749                         return -1;
750                 }
751                 break;
752         case AST_SIP_MEDIA_TRANSPORT_INVALID:
753         case AST_SIP_MEDIA_ENCRYPT_NONE:
754                 break;
755         }
756
757         return 0;
758 }
759
760 /*! \brief Function which negotiates an incoming media stream */
761 static int negotiate_incoming_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
762                                          const struct pjmedia_sdp_session *sdp, const struct pjmedia_sdp_media *stream)
763 {
764         char host[NI_MAXHOST];
765         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
766         enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
767         enum ast_sip_session_media_encryption encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
768         int res;
769
770         /* If port is 0, ignore this media stream */
771         if (!stream->desc.port) {
772                 ast_debug(3, "Media stream '%s' is already declined\n", session_media->stream_type);
773                 return 0;
774         }
775
776         /* If no type formats have been configured reject this stream */
777         if (!ast_format_cap_has_type(session->endpoint->media.codecs, media_type)) {
778                 ast_debug(3, "Endpoint has no codecs for media type '%s', declining stream\n", session_media->stream_type);
779                 return 0;
780         }
781
782         /* Ensure incoming transport is compatible with the endpoint's configuration */
783         if (!session->endpoint->media.rtp.use_received_transport) {
784                 encryption = check_endpoint_media_transport(session->endpoint, stream);
785
786                 if (encryption == AST_SIP_MEDIA_TRANSPORT_INVALID) {
787                         return -1;
788                 }
789         }
790
791         ast_copy_pj_str(host, stream->conn ? &stream->conn->addr : &sdp->conn->addr, sizeof(host));
792
793         /* Ensure that the address provided is valid */
794         if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
795                 /* The provided host was actually invalid so we error out this negotiation */
796                 return -1;
797         }
798
799         /* Using the connection information create an appropriate RTP instance */
800         if (!session_media->rtp && create_rtp(session, session_media, ast_sockaddr_is_ipv6(addrs))) {
801                 return -1;
802         }
803
804         res = setup_media_encryption(session, session_media, sdp, stream);
805         if (res) {
806                 if (!session->endpoint->media.rtp.encryption_optimistic) {
807                         /* If optimistic encryption is disabled and crypto should have been enabled
808                          * but was not this session must fail.
809                          */
810                         return -1;
811                 }
812                 /* There is no encryption, sad. */
813                 session_media->encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
814         }
815
816         /* If we've been explicitly configured to use the received transport OR if
817          * encryption is on and crypto is present use the received transport.
818          * This is done in case of optimistic because it may come in as RTP/AVP or RTP/SAVP depending
819          * on the configuration of the remote endpoint (optimistic themselves or mandatory).
820          */
821         if ((session->endpoint->media.rtp.use_received_transport) ||
822                 ((encryption == AST_SIP_MEDIA_ENCRYPT_SDES) && !res)) {
823                 pj_strdup(session->inv_session->pool, &session_media->transport, &stream->desc.transport);
824         }
825
826         if (set_caps(session, session_media, stream)) {
827                 return 0;
828         }
829         return 1;
830 }
831
832 static int add_crypto_to_stream(struct ast_sip_session *session,
833         struct ast_sip_session_media *session_media,
834         pj_pool_t *pool, pjmedia_sdp_media *media)
835 {
836         pj_str_t stmp;
837         pjmedia_sdp_attr *attr;
838         enum ast_rtp_dtls_hash hash;
839         const char *crypto_attribute;
840         struct ast_rtp_engine_dtls *dtls;
841         static const pj_str_t STR_NEW = { "new", 3 };
842         static const pj_str_t STR_EXISTING = { "existing", 8 };
843         static const pj_str_t STR_ACTIVE = { "active", 6 };
844         static const pj_str_t STR_PASSIVE = { "passive", 7 };
845         static const pj_str_t STR_ACTPASS = { "actpass", 7 };
846         static const pj_str_t STR_HOLDCONN = { "holdconn", 8 };
847
848         switch (session_media->encryption) {
849         case AST_SIP_MEDIA_ENCRYPT_NONE:
850         case AST_SIP_MEDIA_TRANSPORT_INVALID:
851                 break;
852         case AST_SIP_MEDIA_ENCRYPT_SDES:
853                 if (!session_media->srtp) {
854                         session_media->srtp = ast_sdp_srtp_alloc();
855                         if (!session_media->srtp) {
856                                 return -1;
857                         }
858                 }
859
860                 crypto_attribute = ast_sdp_srtp_get_attrib(session_media->srtp,
861                         0 /* DTLS running? No */,
862                         session->endpoint->media.rtp.srtp_tag_32 /* 32 byte tag length? */);
863                 if (!crypto_attribute) {
864                         /* No crypto attribute to add, bad news */
865                         return -1;
866                 }
867
868                 attr = pjmedia_sdp_attr_create(pool, "crypto", pj_cstr(&stmp, crypto_attribute));
869                 media->attr[media->attr_count++] = attr;
870                 break;
871         case AST_SIP_MEDIA_ENCRYPT_DTLS:
872                 if (setup_dtls_srtp(session, session_media)) {
873                         return -1;
874                 }
875
876                 dtls = ast_rtp_instance_get_dtls(session_media->rtp);
877                 if (!dtls) {
878                         return -1;
879                 }
880
881                 switch (dtls->get_connection(session_media->rtp)) {
882                 case AST_RTP_DTLS_CONNECTION_NEW:
883                         attr = pjmedia_sdp_attr_create(pool, "connection", &STR_NEW);
884                         media->attr[media->attr_count++] = attr;
885                         break;
886                 case AST_RTP_DTLS_CONNECTION_EXISTING:
887                         attr = pjmedia_sdp_attr_create(pool, "connection", &STR_EXISTING);
888                         media->attr[media->attr_count++] = attr;
889                         break;
890                 default:
891                         break;
892                 }
893
894                 switch (dtls->get_setup(session_media->rtp)) {
895                 case AST_RTP_DTLS_SETUP_ACTIVE:
896                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_ACTIVE);
897                         media->attr[media->attr_count++] = attr;
898                         break;
899                 case AST_RTP_DTLS_SETUP_PASSIVE:
900                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_PASSIVE);
901                         media->attr[media->attr_count++] = attr;
902                         break;
903                 case AST_RTP_DTLS_SETUP_ACTPASS:
904                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_ACTPASS);
905                         media->attr[media->attr_count++] = attr;
906                         break;
907                 case AST_RTP_DTLS_SETUP_HOLDCONN:
908                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_HOLDCONN);
909                         media->attr[media->attr_count++] = attr;
910                         break;
911                 default:
912                         break;
913                 }
914
915                 hash = dtls->get_fingerprint_hash(session_media->rtp);
916                 crypto_attribute = dtls->get_fingerprint(session_media->rtp);
917                 if (crypto_attribute && (hash == AST_RTP_DTLS_HASH_SHA1 || hash == AST_RTP_DTLS_HASH_SHA256)) {
918                         RAII_VAR(struct ast_str *, fingerprint, ast_str_create(64), ast_free);
919                         if (!fingerprint) {
920                                 return -1;
921                         }
922
923                         if (hash == AST_RTP_DTLS_HASH_SHA1) {
924                                 ast_str_set(&fingerprint, 0, "SHA-1 %s", crypto_attribute);
925                         } else {
926                                 ast_str_set(&fingerprint, 0, "SHA-256 %s", crypto_attribute);
927                         }
928
929                         attr = pjmedia_sdp_attr_create(pool, "fingerprint", pj_cstr(&stmp, ast_str_buffer(fingerprint)));
930                         media->attr[media->attr_count++] = attr;
931                 }
932                 break;
933         }
934
935         return 0;
936 }
937
938 /*! \brief Function which creates an outgoing stream */
939 static int create_outgoing_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
940                                       struct pjmedia_sdp_session *sdp)
941 {
942         pj_pool_t *pool = session->inv_session->pool_prov;
943         static const pj_str_t STR_IN = { "IN", 2 };
944         static const pj_str_t STR_IP4 = { "IP4", 3};
945         static const pj_str_t STR_IP6 = { "IP6", 3};
946         static const pj_str_t STR_SENDRECV = { "sendrecv", 8 };
947         static const pj_str_t STR_SENDONLY = { "sendonly", 8 };
948         pjmedia_sdp_media *media;
949         char hostip[PJ_INET6_ADDRSTRLEN+2];
950         struct ast_sockaddr addr;
951         char tmp[512];
952         pj_str_t stmp;
953         pjmedia_sdp_attr *attr;
954         int index = 0;
955         int noncodec = (session->endpoint->dtmf == AST_SIP_DTMF_RFC_4733) ? AST_RTP_DTMF : 0;
956         int min_packet_size = 0, max_packet_size = 0;
957         int rtp_code;
958         RAII_VAR(struct ast_format_cap *, caps, NULL, ao2_cleanup);
959         enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
960         int use_override_prefs = ast_format_cap_count(session->req_caps);
961
962         int direct_media_enabled = !ast_sockaddr_isnull(&session_media->direct_media_addr) &&
963                 ast_format_cap_count(session->direct_media_cap);
964
965         if ((use_override_prefs && !ast_format_cap_has_type(session->req_caps, media_type)) ||
966             (!use_override_prefs && !ast_format_cap_has_type(session->endpoint->media.codecs, media_type))) {
967                 /* If no type formats are configured don't add a stream */
968                 return 0;
969         } else if (!session_media->rtp && create_rtp(session, session_media, session->endpoint->media.rtp.ipv6)) {
970                 return -1;
971         }
972
973         if (!(media = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_media))) ||
974                 !(media->conn = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_conn)))) {
975                 return -1;
976         }
977
978         if (add_crypto_to_stream(session, session_media, pool, media)) {
979                 return -1;
980         }
981
982         media->desc.media = pj_str(session_media->stream_type);
983         if (pj_strlen(&session_media->transport)) {
984                 /* If a transport has already been specified use it */
985                 media->desc.transport = session_media->transport;
986         } else {
987                 media->desc.transport = pj_str(ast_sdp_get_rtp_profile(
988                         /* Optimistic encryption places crypto in the normal RTP/AVP profile */
989                         !session->endpoint->media.rtp.encryption_optimistic &&
990                                 (session_media->encryption == AST_SIP_MEDIA_ENCRYPT_SDES),
991                         session_media->rtp, session->endpoint->media.rtp.use_avpf,
992                         session->endpoint->media.rtp.force_avp));
993         }
994
995         /* Add connection level details */
996         if (direct_media_enabled) {
997                 ast_copy_string(hostip, ast_sockaddr_stringify_fmt(&session_media->direct_media_addr, AST_SOCKADDR_STR_ADDR), sizeof(hostip));
998         } else if (ast_strlen_zero(session->endpoint->media.address)) {
999                 pj_sockaddr localaddr;
1000
1001                 if (pj_gethostip(session->endpoint->media.rtp.ipv6 ? pj_AF_INET6() : pj_AF_INET(), &localaddr)) {
1002                         return -1;
1003                 }
1004                 pj_sockaddr_print(&localaddr, hostip, sizeof(hostip), 2);
1005         } else {
1006                 ast_copy_string(hostip, session->endpoint->media.address, sizeof(hostip));
1007         }
1008
1009         media->conn->net_type = STR_IN;
1010         media->conn->addr_type = session->endpoint->media.rtp.ipv6 ? STR_IP6 : STR_IP4;
1011         pj_strdup2(pool, &media->conn->addr, hostip);
1012         ast_rtp_instance_get_local_address(session_media->rtp, &addr);
1013         media->desc.port = direct_media_enabled ? ast_sockaddr_port(&session_media->direct_media_addr) : (pj_uint16_t) ast_sockaddr_port(&addr);
1014         media->desc.port_count = 1;
1015
1016         /* Add ICE attributes and candidates */
1017         add_ice_to_stream(session, session_media, pool, media);
1018
1019         if (!(caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1020                 ast_log(LOG_ERROR, "Failed to allocate %s capabilities\n", session_media->stream_type);
1021                 return -1;
1022         }
1023
1024         if (direct_media_enabled) {
1025                 ast_format_cap_get_compatible(session->endpoint->media.codecs, session->direct_media_cap, caps);
1026         } else if (!ast_format_cap_count(session->req_caps) ||
1027                 !ast_format_cap_iscompatible(session->req_caps, session->endpoint->media.codecs)) {
1028                 ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, media_type);
1029         } else {
1030                 ast_format_cap_append_from_cap(caps, session->req_caps, media_type);
1031         }
1032
1033         for (index = 0; index < ast_format_cap_count(caps); ++index) {
1034                 struct ast_format *format = ast_format_cap_get_format(caps, index);
1035
1036                 if (ast_format_get_type(format) != media_type) {
1037                         ao2_ref(format, -1);
1038                         continue;
1039                 }
1040
1041                 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(session_media->rtp), 1, format, 0)) == -1) {
1042                         ast_log(LOG_WARNING,"Unable to get rtp codec payload code for %s\n", ast_format_get_name(format));
1043                         ao2_ref(format, -1);
1044                         continue;
1045                 }
1046
1047                 if (!(attr = generate_rtpmap_attr(media, pool, rtp_code, 1, format, 0))) {
1048                         ao2_ref(format, -1);
1049                         continue;
1050                 }
1051                 media->attr[media->attr_count++] = attr;
1052
1053                 if ((attr = generate_fmtp_attr(pool, format, rtp_code))) {
1054                         media->attr[media->attr_count++] = attr;
1055                 }
1056
1057                 if (ast_format_get_maximum_ms(format) &&
1058                         ((ast_format_get_maximum_ms(format) < max_packet_size) || !max_packet_size)) {
1059                         max_packet_size = ast_format_get_maximum_ms(format);
1060                 }
1061                 ao2_ref(format, -1);
1062         }
1063
1064         /* Add non-codec formats */
1065         if (media_type != AST_MEDIA_TYPE_VIDEO) {
1066                 for (index = 1LL; index <= AST_RTP_MAX; index <<= 1) {
1067                         if (!(noncodec & index) || (rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(session_media->rtp),
1068                                                                                            0, NULL, index)) == -1) {
1069                                 continue;
1070                         }
1071
1072                         if (!(attr = generate_rtpmap_attr(media, pool, rtp_code, 0, NULL, index))) {
1073                                 continue;
1074                         }
1075
1076                         media->attr[media->attr_count++] = attr;
1077
1078                         if (index == AST_RTP_DTMF) {
1079                                 snprintf(tmp, sizeof(tmp), "%d 0-16", rtp_code);
1080                                 attr = pjmedia_sdp_attr_create(pool, "fmtp", pj_cstr(&stmp, tmp));
1081                                 media->attr[media->attr_count++] = attr;
1082                         }
1083                 }
1084         }
1085
1086         /* If no formats were actually added to the media stream don't add it to the SDP */
1087         if (!media->desc.fmt_count) {
1088                 return 1;
1089         }
1090
1091         /* If ptime is set add it as an attribute */
1092         min_packet_size = ast_rtp_codecs_get_framing(ast_rtp_instance_get_codecs(session_media->rtp));
1093         if (!min_packet_size) {
1094                 min_packet_size = ast_format_cap_get_framing(caps);
1095         }
1096         if (min_packet_size) {
1097                 snprintf(tmp, sizeof(tmp), "%d", min_packet_size);
1098                 attr = pjmedia_sdp_attr_create(pool, "ptime", pj_cstr(&stmp, tmp));
1099                 media->attr[media->attr_count++] = attr;
1100         }
1101
1102         if (max_packet_size) {
1103                 snprintf(tmp, sizeof(tmp), "%d", max_packet_size);
1104                 attr = pjmedia_sdp_attr_create(pool, "maxptime", pj_cstr(&stmp, tmp));
1105                 media->attr[media->attr_count++] = attr;
1106         }
1107
1108         /* Add the sendrecv attribute - we purposely don't keep track because pjmedia-sdp will automatically change our offer for us */
1109         attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr);
1110         attr->name = !session_media->locally_held ? STR_SENDRECV : STR_SENDONLY;
1111         media->attr[media->attr_count++] = attr;
1112
1113         /* Add the media stream to the SDP */
1114         sdp->media[sdp->media_count++] = media;
1115
1116         return 1;
1117 }
1118
1119 static int apply_negotiated_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
1120                                        const struct pjmedia_sdp_session *local, const struct pjmedia_sdp_media *local_stream,
1121                                        const struct pjmedia_sdp_session *remote, const struct pjmedia_sdp_media *remote_stream)
1122 {
1123         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
1124         enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
1125         char host[NI_MAXHOST];
1126         int fdno, res;
1127
1128         if (!session->channel) {
1129                 return 1;
1130         }
1131
1132         if (!local_stream->desc.port || !remote_stream->desc.port) {
1133                 return 1;
1134         }
1135
1136         /* Ensure incoming transport is compatible with the endpoint's configuration */
1137         if (!session->endpoint->media.rtp.use_received_transport &&
1138                 check_endpoint_media_transport(session->endpoint, remote_stream) == AST_SIP_MEDIA_TRANSPORT_INVALID) {
1139                 return -1;
1140         }
1141
1142         /* Create an RTP instance if need be */
1143         if (!session_media->rtp && create_rtp(session, session_media, session->endpoint->media.rtp.ipv6)) {
1144                 return -1;
1145         }
1146
1147         res = setup_media_encryption(session, session_media, remote, remote_stream);
1148         if (!session->endpoint->media.rtp.encryption_optimistic && res) {
1149                 /* If optimistic encryption is disabled and crypto should have been enabled but was not
1150                  * this session must fail.
1151                  */
1152                 return -1;
1153         }
1154
1155         if (!remote_stream->conn && !remote->conn) {
1156                 return 1;
1157         }
1158
1159         ast_copy_pj_str(host, remote_stream->conn ? &remote_stream->conn->addr : &remote->conn->addr, sizeof(host));
1160
1161         /* Ensure that the address provided is valid */
1162         if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
1163                 /* The provided host was actually invalid so we error out this negotiation */
1164                 return -1;
1165         }
1166
1167         /* Apply connection information to the RTP instance */
1168         ast_sockaddr_set_port(addrs, remote_stream->desc.port);
1169         ast_rtp_instance_set_remote_address(session_media->rtp, addrs);
1170         if (set_caps(session, session_media, local_stream)) {
1171                 return 1;
1172         }
1173
1174         if ((fdno = media_type_to_fdno(media_type)) < 0) {
1175                 return -1;
1176         }
1177         ast_channel_set_fd(session->channel, fdno, ast_rtp_instance_fd(session_media->rtp, 0));
1178         ast_channel_set_fd(session->channel, fdno + 1, ast_rtp_instance_fd(session_media->rtp, 1));
1179
1180         /* If ICE support is enabled find all the needed attributes */
1181         process_ice_attributes(session, session_media, remote, remote_stream);
1182
1183         /* Ensure the RTP instance is active */
1184         ast_rtp_instance_activate(session_media->rtp);
1185
1186         /* audio stream handles music on hold */
1187         if (media_type != AST_MEDIA_TYPE_AUDIO) {
1188                 if ((pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_FALSE)
1189                         && (session->inv_session->state == PJSIP_INV_STATE_CONFIRMED)) {
1190                         ast_queue_control(session->channel, AST_CONTROL_UPDATE_RTP_PEER);
1191                 }
1192                 return 1;
1193         }
1194
1195         if (ast_sockaddr_isnull(addrs) ||
1196                 ast_sockaddr_is_any(addrs) ||
1197                 pjmedia_sdp_media_find_attr2(remote_stream, "sendonly", NULL) ||
1198                 pjmedia_sdp_media_find_attr2(remote_stream, "inactive", NULL)) {
1199                 if (!session_media->remotely_held) {
1200                         /* The remote side has put us on hold */
1201                         ast_queue_hold(session->channel, session->endpoint->mohsuggest);
1202                         ast_rtp_instance_stop(session_media->rtp);
1203                         ast_queue_frame(session->channel, &ast_null_frame);
1204                         session_media->remotely_held = 1;
1205                 }
1206         } else if (session_media->remotely_held) {
1207                 /* The remote side has taken us off hold */
1208                 ast_queue_unhold(session->channel);
1209                 ast_queue_frame(session->channel, &ast_null_frame);
1210                 session_media->remotely_held = 0;
1211         } else if ((pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_FALSE)
1212                 && (session->inv_session->state == PJSIP_INV_STATE_CONFIRMED)) {
1213                 ast_queue_control(session->channel, AST_CONTROL_UPDATE_RTP_PEER);
1214         }
1215
1216         /* This purposely resets the encryption to the configured in case it gets added later */
1217         session_media->encryption = session->endpoint->media.rtp.encryption;
1218
1219         return 1;
1220 }
1221
1222 /*! \brief Function which updates the media stream with external media address, if applicable */
1223 static void change_outgoing_sdp_stream_media_address(pjsip_tx_data *tdata, struct pjmedia_sdp_media *stream, struct ast_sip_transport *transport)
1224 {
1225         char host[NI_MAXHOST];
1226         struct ast_sockaddr addr = { { 0, } };
1227
1228         /* If the stream has been rejected there will be no connection line */
1229         if (!stream->conn) {
1230                 return;
1231         }
1232
1233         ast_copy_pj_str(host, &stream->conn->addr, sizeof(host));
1234         ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID);
1235
1236         /* Is the address within the SDP inside the same network? */
1237         if (ast_apply_ha(transport->localnet, &addr) == AST_SENSE_ALLOW) {
1238                 return;
1239         }
1240
1241         pj_strdup2(tdata->pool, &stream->conn->addr, transport->external_media_address);
1242 }
1243
1244 /*! \brief Function which destroys the RTP instance when session ends */
1245 static void stream_destroy(struct ast_sip_session_media *session_media)
1246 {
1247         if (session_media->rtp) {
1248                 ast_rtp_instance_stop(session_media->rtp);
1249                 ast_rtp_instance_destroy(session_media->rtp);
1250         }
1251         session_media->rtp = NULL;
1252 }
1253
1254 /*! \brief SDP handler for 'audio' media stream */
1255 static struct ast_sip_session_sdp_handler audio_sdp_handler = {
1256         .id = STR_AUDIO,
1257         .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
1258         .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
1259         .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
1260         .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
1261         .stream_destroy = stream_destroy,
1262 };
1263
1264 /*! \brief SDP handler for 'video' media stream */
1265 static struct ast_sip_session_sdp_handler video_sdp_handler = {
1266         .id = STR_VIDEO,
1267         .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
1268         .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
1269         .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
1270         .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
1271         .stream_destroy = stream_destroy,
1272 };
1273
1274 static int video_info_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
1275 {
1276         struct pjsip_transaction *tsx;
1277         pjsip_tx_data *tdata;
1278
1279         if (!session->channel
1280                 || !ast_sip_is_content_type(&rdata->msg_info.msg->body->content_type,
1281                         "application",
1282                         "media_control+xml")) {
1283                 return 0;
1284         }
1285
1286         tsx = pjsip_rdata_get_tsx(rdata);
1287
1288         ast_queue_control(session->channel, AST_CONTROL_VIDUPDATE);
1289
1290         if (pjsip_dlg_create_response(session->inv_session->dlg, rdata, 200, NULL, &tdata) == PJ_SUCCESS) {
1291                 pjsip_dlg_send_response(session->inv_session->dlg, tsx, tdata);
1292         }
1293
1294         return 0;
1295 }
1296
1297 static struct ast_sip_session_supplement video_info_supplement = {
1298         .method = "INFO",
1299         .incoming_request = video_info_incoming_request,
1300 };
1301
1302 /*! \brief Unloads the sdp RTP/AVP module from Asterisk */
1303 static int unload_module(void)
1304 {
1305         ast_sip_session_unregister_supplement(&video_info_supplement);
1306         ast_sip_session_unregister_sdp_handler(&video_sdp_handler, STR_VIDEO);
1307         ast_sip_session_unregister_sdp_handler(&audio_sdp_handler, STR_AUDIO);
1308
1309         if (sched) {
1310                 ast_sched_context_destroy(sched);
1311         }
1312
1313         return 0;
1314 }
1315
1316 /*!
1317  * \brief Load the module
1318  *
1319  * Module loading including tests for configuration or dependencies.
1320  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1321  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1322  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
1323  * configuration file or other non-critical problem return
1324  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1325  */
1326 static int load_module(void)
1327 {
1328         CHECK_PJSIP_SESSION_MODULE_LOADED();
1329
1330         ast_sockaddr_parse(&address_ipv4, "0.0.0.0", 0);
1331         ast_sockaddr_parse(&address_ipv6, "::", 0);
1332
1333         if (!(sched = ast_sched_context_create())) {
1334                 ast_log(LOG_ERROR, "Unable to create scheduler context.\n");
1335                 goto end;
1336         }
1337
1338         if (ast_sched_start_thread(sched)) {
1339                 ast_log(LOG_ERROR, "Unable to create scheduler context thread.\n");
1340                 goto end;
1341         }
1342
1343         if (ast_sip_session_register_sdp_handler(&audio_sdp_handler, STR_AUDIO)) {
1344                 ast_log(LOG_ERROR, "Unable to register SDP handler for %s stream type\n", STR_AUDIO);
1345                 goto end;
1346         }
1347
1348         if (ast_sip_session_register_sdp_handler(&video_sdp_handler, STR_VIDEO)) {
1349                 ast_log(LOG_ERROR, "Unable to register SDP handler for %s stream type\n", STR_VIDEO);
1350                 goto end;
1351         }
1352
1353         ast_sip_session_register_supplement(&video_info_supplement);
1354
1355         return AST_MODULE_LOAD_SUCCESS;
1356 end:
1357         unload_module();
1358
1359         return AST_MODULE_LOAD_FAILURE;
1360 }
1361
1362 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP SDP RTP/AVP stream handler",
1363                 .support_level = AST_MODULE_SUPPORT_CORE,
1364                 .load = load_module,
1365                 .unload = unload_module,
1366                 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
1367         );