39#include <arpa/nameser.h>
50#include <openssl/opensslconf.h>
51#include <openssl/opensslv.h>
52#if !defined(OPENSSL_NO_SRTP) && (OPENSSL_VERSION_NUMBER >= 0x10001000L)
53#include <openssl/ssl.h>
54#include <openssl/err.h>
55#include <openssl/bio.h>
56#if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L)
57#include <openssl/bn.h>
60#include <openssl/dh.h>
67#include <pjlib-util.h>
98#define MAX_TIMESTAMP_SKEW 640
100#define RTP_SEQ_MOD (1<<16)
101#define RTCP_DEFAULT_INTERVALMS 5000
102#define RTCP_MIN_INTERVALMS 500
103#define RTCP_MAX_INTERVALMS 60000
105#define DEFAULT_RTP_START 5000
106#define DEFAULT_RTP_END 31000
108#define MINIMUM_RTP_PORT 1024
109#define MAXIMUM_RTP_PORT 65535
111#define DEFAULT_TURN_PORT 3478
113#define TURN_STATE_WAIT_TIME 2000
115#define DEFAULT_RTP_SEND_BUFFER_SIZE 250
116#define MAXIMUM_RTP_SEND_BUFFER_SIZE (DEFAULT_RTP_SEND_BUFFER_SIZE + 200)
117#define DEFAULT_RTP_RECV_BUFFER_SIZE 20
118#define MAXIMUM_RTP_RECV_BUFFER_SIZE (DEFAULT_RTP_RECV_BUFFER_SIZE + 20)
119#define OLD_PACKET_COUNT 1000
120#define MISSING_SEQNOS_ADDED_TRIGGER 2
122#define SEQNO_CYCLE_OVER 65536
125#define RTCP_PT_FUR 192
127#define RTCP_PT_SR AST_RTP_RTCP_SR
129#define RTCP_PT_RR AST_RTP_RTCP_RR
131#define RTCP_PT_SDES 202
133#define RTCP_PT_BYE 203
135#define RTCP_PT_APP 204
138#define RTCP_PT_PSFB AST_RTP_RTCP_PSFB
142#define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000))
144#define ZFONE_PROFILE_ID 0x505a
146#define DEFAULT_LEARNING_MIN_SEQUENTIAL 4
159#define CALC_LEARNING_MIN_DURATION(count) (((count) - 1) * 9 - 5)
160#define DEFAULT_LEARNING_MIN_DURATION CALC_LEARNING_MIN_DURATION(DEFAULT_LEARNING_MIN_SEQUENTIAL)
162#define SRTP_MASTER_KEY_LEN 16
163#define SRTP_MASTER_SALT_LEN 14
164#define SRTP_MASTER_LEN (SRTP_MASTER_KEY_LEN + SRTP_MASTER_SALT_LEN)
166#define RTP_DTLS_ESTABLISHED -37
187#define STRICT_RTP_LEARN_TIMEOUT 5000
189#define DEFAULT_STRICT_RTP STRICT_RTP_YES
190#define DEFAULT_SRTP_REPLAY_PROTECTION 1
191#define DEFAULT_ICESUPPORT 1
192#define DEFAULT_STUN_SOFTWARE_ATTRIBUTE 1
193#define DEFAULT_DTLS_MTU 1200
203#define RTP_IGNORE_FIRST_PACKETS_COUNT 15
219static int nochecksums;
225#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
231static struct sockaddr_in stunaddr;
232static pj_str_t turnaddr;
234static pj_str_t turnusername;
235static pj_str_t turnpassword;
255static pj_pool_t *pool;
258static pj_timer_heap_t *timer_heap;
261static pj_thread_t *timer_thread;
264static int timer_terminate;
267struct ast_rtp_ioqueue_thread {
273 pj_ioqueue_t *ioqueue;
275 pj_timer_heap_t *timerheap;
288struct ast_ice_host_candidate {
291 unsigned int include_local;
302#define FLAG_3389_WARNING (1 << 0)
303#define FLAG_NAT_ACTIVE (3 << 1)
304#define FLAG_NAT_INACTIVE (0 << 1)
305#define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
306#define FLAG_NEED_MARKER_BIT (1 << 3)
307#define FLAG_DTMF_COMPENSATE (1 << 4)
308#define FLAG_REQ_LOCAL_BRIDGE_BIT (1 << 5)
310#define TRANSPORT_SOCKET_RTP 0
311#define TRANSPORT_SOCKET_RTCP 1
312#define TRANSPORT_TURN_RTP 2
313#define TRANSPORT_TURN_RTCP 3
326#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
340 pj_ice_sess *real_ice;
484 struct ice_wrap *ice;
486 pj_turn_sock *turn_rtp;
487 pj_turn_sock *turn_rtcp;
488 pj_turn_state_t turn_state;
489 unsigned int passthrough:1;
490 unsigned int rtp_passthrough:1;
491 unsigned int rtcp_passthrough:1;
492 unsigned int ice_port;
496 struct ast_rtp_ioqueue_thread *ioqueue;
498 char remote_ufrag[256];
499 char remote_passwd[256];
501 char local_ufrag[256];
502 char local_passwd[256];
508 unsigned int ice_num_components;
509 unsigned int ice_media_started:1;
512#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
517 char local_fingerprint[160];
519 unsigned char remote_fingerprint[EVP_MAX_MD_SIZE];
522 struct dtls_details dtls;
604#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
605 struct dtls_details dtls;
674#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
678static int dtls_bio_write(BIO *bio,
const char *
buf,
int len);
679static long dtls_bio_ctrl(BIO *bio,
int cmd,
long arg1,
void *arg2);
680static int dtls_bio_new(BIO *bio);
681static int dtls_bio_free(BIO *bio);
683#ifndef HAVE_OPENSSL_BIO_METHOD
684static BIO_METHOD dtls_bio_methods = {
685 .type = BIO_TYPE_BIO,
687 .bwrite = dtls_bio_write,
688 .ctrl = dtls_bio_ctrl,
689 .create = dtls_bio_new,
690 .destroy = dtls_bio_free,
693static BIO_METHOD *dtls_bio_methods;
700static void stunaddr_resolve_callback(
const struct ast_dns_query *query);
701static int store_stunaddr_resolved(
const struct ast_dns_query *query);
704#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
705static int dtls_bio_new(BIO *bio)
707#ifdef HAVE_OPENSSL_BIO_METHOD
708 BIO_set_init(bio, 1);
709 BIO_set_data(bio,
NULL);
710 BIO_set_shutdown(bio, 0);
719static int dtls_bio_free(BIO *bio)
725#ifdef HAVE_OPENSSL_BIO_METHOD
726 BIO_set_data(bio,
NULL);
733static int dtls_bio_write(BIO *bio,
const char *
buf,
int len)
735#ifdef HAVE_OPENSSL_BIO_METHOD
750 if (rtp->
rtcp && rtp->
rtcp->dtls.write_bio == bio) {
761 bytes_sent =
__rtp_sendto(instance, (
char *)
buf,
len, 0, &remote_address, rtcp, &ice, 0);
764 ast_debug(0,
"(%p) DTLS - sent %s packet to %s%s (len %-6.6d)\n",
766 ice ?
" (via ICE)" :
"", bytes_sent);
772static long dtls_bio_ctrl(BIO *bio,
int cmd,
long arg1,
void *arg2)
777 case BIO_CTRL_DGRAM_QUERY_MTU:
779 case BIO_CTRL_WPENDING:
780 case BIO_CTRL_PENDING:
791static void host_candidate_overrides_clear(
void)
793 struct ast_ice_host_candidate *candidate;
808 char address[PJ_INET6_ADDRSTRLEN];
810 if (component < 1 || !ice->comp[component - 1].valid_check) {
815 pj_sockaddr_print(&ice->comp[component - 1].valid_check->rcand->addr,
address,
818 pj_sockaddr_get_port(&ice->comp[component - 1].valid_check->rcand->addr));
822static void ast_rtp_ice_candidate_destroy(
void *obj)
836static void ast_rtp_ice_set_authentication(
struct ast_rtp_instance *instance,
const char *ufrag,
const char *password)
839 int ice_attrb_reset = 0;
842 if (!
ast_strlen_zero(rtp->remote_ufrag) && strcmp(ufrag, rtp->remote_ufrag)) {
849 if (!
ast_strlen_zero(rtp->remote_passwd) && strcmp(password, rtp->remote_passwd)) {
852 ast_copy_string(rtp->remote_passwd, password,
sizeof(rtp->remote_passwd));
856 if (ice_attrb_reset) {
862static int ice_candidate_cmp(
void *obj,
void *arg,
int flags)
866 if (strcmp(candidate1->
foundation, candidate2->foundation) ||
867 candidate1->
id != candidate2->id ||
868 candidate1->
type != candidate2->type ||
883 if (strcasecmp(candidate->
transport,
"udp")) {
887 if (!rtp->ice_proposed_remote_candidates) {
890 if (!rtp->ice_proposed_remote_candidates) {
900 if (!(remote_candidate =
ao2_alloc(
sizeof(*remote_candidate), ast_rtp_ice_candidate_destroy))) {
905 remote_candidate->
id = candidate->
id;
910 remote_candidate->
type = candidate->
type;
912 ast_debug_ice(2,
"(%p) ICE add remote candidate\n", instance);
914 ao2_link(rtp->ice_proposed_remote_candidates, remote_candidate);
921static void pj_thread_register_check(
void)
923 pj_thread_desc *
desc;
926 if (pj_thread_is_registered() == PJ_TRUE) {
932 ast_log(
LOG_ERROR,
"Could not get thread desc from thread-local storage. Expect awful things to occur\n");
937 if (pj_thread_register(
"Asterisk Thread", *
desc, &
thread) != PJ_SUCCESS) {
950 struct ice_wrap *ice;
972static void ice_wrap_dtor(
void *vdoomed)
974 struct ice_wrap *ice = vdoomed;
977 pj_thread_register_check();
979 pj_ice_sess_destroy(ice->real_ice);
983static void ast2pj_rtp_ice_role(
enum ast_rtp_ice_role ast_role,
enum pj_ice_sess_role *pj_role)
987 *pj_role = PJ_ICE_SESS_ROLE_CONTROLLED;
990 *pj_role = PJ_ICE_SESS_ROLE_CONTROLLING;
995static void pj2ast_rtp_ice_role(
enum pj_ice_sess_role pj_role,
enum ast_rtp_ice_role *ast_role)
998 case PJ_ICE_SESS_ROLE_CONTROLLED:
1001 case PJ_ICE_SESS_ROLE_CONTROLLING:
1004 case PJ_ICE_SESS_ROLE_UNKNOWN:
1021 if (!rtp->ice->real_ice->is_nominating && !rtp->ice->real_ice->is_complete) {
1022 ast_debug_ice(3,
" (%p) ICE nevermind, not ready for a reset\n", instance);
1026 ast_debug_ice(3,
"(%p) ICE recreating ICE session %s (%d)\n",
1028 res = ice_create(instance, &rtp->ice_original_rtp_addr, rtp->ice_port, 1);
1031 enum pj_ice_sess_role role = PJ_ICE_SESS_ROLE_UNKNOWN;
1032 ast2pj_rtp_ice_role(rtp->role, &role);
1033 pj_ice_sess_change_role(rtp->ice->real_ice, role);
1039 if (rtp->ice_num_components == 1 && rtp->turn_rtcp) {
1041 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
1043 rtp->turn_state = PJ_TURN_STATE_NULL;
1047 pj_turn_sock_destroy(rtp->turn_rtcp);
1049 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
1054 rtp->ice_media_started = 0;
1072 if (!left_candidate) {
1090 pj_str_t ufrag = pj_str(rtp->remote_ufrag), passwd = pj_str(rtp->remote_passwd);
1091 pj_ice_sess_cand candidates[PJ_ICE_MAX_CAND];
1094 int cand_cnt = 0, has_rtp = 0, has_rtcp = 0;
1096 if (!rtp->ice || !rtp->ice_proposed_remote_candidates) {
1101 if (rtp->ice_active_remote_candidates &&
1102 !ice_candidates_compare(rtp->ice_proposed_remote_candidates, rtp->ice_active_remote_candidates)) {
1103 ast_debug_ice(2,
"(%p) ICE proposed equals active candidates\n", instance);
1105 rtp->ice_proposed_remote_candidates =
NULL;
1107 pj2ast_rtp_ice_role(rtp->ice->real_ice->role, &rtp->role);
1113 rtp->ice_active_remote_candidates = rtp->ice_proposed_remote_candidates;
1114 rtp->ice_proposed_remote_candidates =
NULL;
1119 if (ice_reset_session(instance)) {
1120 ast_log(
LOG_NOTICE,
"(%p) ICE failed to create replacement session\n", instance);
1124 pj_thread_register_check();
1135 pj_strdup2(rtp->ice->real_ice->pool, &candidates[cand_cnt].foundation,
1137 candidates[cand_cnt].comp_id = candidate->
id;
1138 candidates[cand_cnt].prio = candidate->
priority;
1147 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_HOST;
1149 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_SRFLX;
1151 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_RELAYED;
1158 pj_turn_sock_set_perm(rtp->turn_rtp, 1, &candidates[cand_cnt].addr, 1);
1164 pj_turn_sock_set_perm(rtp->turn_rtcp, 1, &candidates[cand_cnt].addr, 1);
1175 ast_log(
LOG_WARNING,
"(%p) ICE lost %d candidates. Consider increasing PJ_ICE_MAX_CAND in PJSIP\n",
1184 if (!has_rtcp && rtp->ice_num_components > 1) {
1188 if (rtp->ice && has_rtp && (has_rtcp || rtp->ice_num_components == 1)) {
1191 struct ice_wrap *ice;
1197 res = pj_ice_sess_create_check_list(ice->real_ice, &ufrag, &passwd, cand_cnt, &candidates[0]);
1198 if (res == PJ_SUCCESS) {
1199 ast_debug_ice(2,
"(%p) ICE successfully created checklist\n", instance);
1201 pj_ice_sess_start_check(ice->real_ice);
1202 pj_timer_heap_poll(timer_heap,
NULL);
1211 pj_strerror(res, reason,
sizeof(reason));
1212 ast_log(
LOG_WARNING,
"(%p) ICE failed to create session check list: %s\n", instance, reason);
1221 ao2_ref(rtp->ice_active_remote_candidates, -1);
1222 rtp->ice_active_remote_candidates =
NULL;
1224 rtp->ice->real_ice->rcand_cnt = rtp->ice->real_ice->clist.count = 0;
1233 return rtp->local_ufrag;
1237static const char *ast_rtp_ice_get_password(
struct ast_rtp_instance *instance)
1241 return rtp->local_passwd;
1249 if (rtp->ice_local_candidates) {
1250 ao2_ref(rtp->ice_local_candidates, +1);
1253 return rtp->ice_local_candidates;
1265 pj_thread_register_check();
1267 pj_ice_sess_change_role(rtp->ice->real_ice, PJ_ICE_SESS_ROLE_CONTROLLING);
1276 ast_debug_ice(3,
"(%p) ICE set role failed; no ice instance\n", instance);
1282 if (!rtp->ice->real_ice->is_nominating && !rtp->ice->real_ice->is_complete) {
1283 pj_thread_register_check();
1287 PJ_ICE_SESS_ROLE_CONTROLLED : PJ_ICE_SESS_ROLE_CONTROLLING);
1289 ast_debug_ice(2,
"(%p) ICE not setting role because state is %s\n",
1290 instance, rtp->ice->real_ice->is_nominating ?
"nominating" :
"complete");
1296 unsigned comp_id,
unsigned transport_id, pj_ice_cand_type
type, pj_uint16_t local_pref,
1297 const pj_sockaddr_t *addr,
const pj_sockaddr_t *base_addr,
const pj_sockaddr_t *rel_addr,
1300 pj_str_t foundation;
1302 struct ice_wrap *ice;
1303 char address[PJ_INET6_ADDRSTRLEN];
1310 pj_thread_register_check();
1312 pj_ice_calc_foundation(rtp->ice->real_ice->pool, &foundation,
type, addr);
1314 if (!rtp->ice_local_candidates) {
1316 NULL, ice_candidate_cmp);
1317 if (!rtp->ice_local_candidates) {
1322 if (!(candidate =
ao2_alloc(
sizeof(*candidate), ast_rtp_ice_candidate_destroy))) {
1327 candidate->
id = comp_id;
1338 if (
type == PJ_ICE_CAND_TYPE_HOST) {
1340 }
else if (
type == PJ_ICE_CAND_TYPE_SRFLX) {
1342 }
else if (
type == PJ_ICE_CAND_TYPE_RELAYED) {
1356 status = pj_ice_sess_add_cand(ice->real_ice, comp_id, transport_id,
type, local_pref,
1357 &foundation, addr, base_addr, rel_addr, addr_len,
NULL);
1360 if (!rtp->ice ||
status != PJ_SUCCESS) {
1368 candidate->
priority = rtp->ice->real_ice->lcand[rtp->ice->real_ice->lcand_cnt - 1].prio;
1373 ao2_link(rtp->ice_local_candidates, candidate);
1378static void ast_rtp_on_turn_rx_rtp_data(pj_turn_sock *turn_sock,
void *pkt,
unsigned pkt_len,
const pj_sockaddr_t *peer_addr,
unsigned addr_len)
1382 struct ice_wrap *ice;
1393 if (
status != PJ_SUCCESS) {
1401 if (!rtp->rtp_passthrough) {
1404 rtp->rtp_passthrough = 0;
1407 ast_sendto(rtp->
s, pkt, pkt_len, 0, &rtp->rtp_loop);
1411static void ast_rtp_on_turn_rtp_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, pj_turn_state_t new_state)
1426 rtp->turn_state = new_state;
1429 if (new_state == PJ_TURN_STATE_DESTROYING) {
1430 pj_turn_sock_set_user_data(rtp->turn_rtp,
NULL);
1431 rtp->turn_rtp =
NULL;
1438static pj_turn_sock_cb ast_rtp_turn_rtp_sock_cb = {
1439 .on_rx_data = ast_rtp_on_turn_rx_rtp_data,
1440 .on_state = ast_rtp_on_turn_rtp_state,
1444static void ast_rtp_on_turn_rx_rtcp_data(pj_turn_sock *turn_sock,
void *pkt,
unsigned pkt_len,
const pj_sockaddr_t *peer_addr,
unsigned addr_len)
1448 struct ice_wrap *ice;
1459 if (
status != PJ_SUCCESS) {
1467 if (!rtp->rtcp_passthrough) {
1470 rtp->rtcp_passthrough = 0;
1477static void ast_rtp_on_turn_rtcp_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, pj_turn_state_t new_state)
1492 rtp->turn_state = new_state;
1495 if (new_state == PJ_TURN_STATE_DESTROYING) {
1496 pj_turn_sock_set_user_data(rtp->turn_rtcp,
NULL);
1497 rtp->turn_rtcp =
NULL;
1504static pj_turn_sock_cb ast_rtp_turn_rtcp_sock_cb = {
1505 .on_rx_data = ast_rtp_on_turn_rx_rtcp_data,
1506 .on_state = ast_rtp_on_turn_rtcp_state,
1510static int ioqueue_worker_thread(
void *data)
1512 struct ast_rtp_ioqueue_thread *ioqueue = data;
1514 while (!ioqueue->terminate) {
1515 const pj_time_val delay = {0, 10};
1517 pj_ioqueue_poll(ioqueue->ioqueue, &delay);
1519 pj_timer_heap_poll(ioqueue->timerheap,
NULL);
1526static void rtp_ioqueue_thread_destroy(
struct ast_rtp_ioqueue_thread *ioqueue)
1528 if (ioqueue->thread) {
1529 ioqueue->terminate = 1;
1530 pj_thread_join(ioqueue->thread);
1531 pj_thread_destroy(ioqueue->thread);
1534 if (ioqueue->pool) {
1538 pj_pool_t *temp_pool = ioqueue->pool;
1540 ioqueue->pool =
NULL;
1541 pj_pool_release(temp_pool);
1548static void rtp_ioqueue_thread_remove(
struct ast_rtp_ioqueue_thread *ioqueue)
1554 if ((ioqueue->count -= 2) == 0) {
1564 rtp_ioqueue_thread_destroy(ioqueue);
1568static struct ast_rtp_ioqueue_thread *rtp_ioqueue_thread_get_or_create(
void)
1570 struct ast_rtp_ioqueue_thread *ioqueue;
1577 if ((ioqueue->count + 2) < PJ_IOQUEUE_MAX_HANDLES) {
1584 ioqueue->count += 2;
1593 ioqueue->pool = pj_pool_create(&
cachingpool.factory,
"rtp", 512, 512,
NULL);
1598 if (pj_timer_heap_create(ioqueue->pool, 4, &ioqueue->timerheap) != PJ_SUCCESS) {
1602 if (pj_lock_create_recursive_mutex(ioqueue->pool,
"rtp%p", &
lock) != PJ_SUCCESS) {
1606 pj_timer_heap_set_lock(ioqueue->timerheap,
lock, PJ_TRUE);
1608 if (pj_ioqueue_create(ioqueue->pool, PJ_IOQUEUE_MAX_HANDLES, &ioqueue->ioqueue) != PJ_SUCCESS) {
1612 if (pj_thread_create(ioqueue->pool,
"ice", &ioqueue_worker_thread, ioqueue, 0, 0, &ioqueue->thread) != PJ_SUCCESS) {
1624 rtp_ioqueue_thread_destroy(ioqueue);
1634 enum ast_transport transport,
const char *server,
unsigned int port,
const char *username,
const char *password)
1637 pj_turn_sock **turn_sock;
1638 const pj_turn_sock_cb *turn_cb;
1639 pj_turn_tp_type conn_type;
1641 pj_stun_auth_cred cred = { 0, };
1644 pj_stun_config stun_config;
1646 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
1647 pj_turn_session_info
info;
1650 pj_turn_sock_cfg turn_sock_cfg;
1651 struct ice_wrap *ice;
1662 turn_sock = &rtp->turn_rtp;
1663 turn_cb = &ast_rtp_turn_rtp_sock_cb;
1667 turn_sock = &rtp->turn_rtcp;
1668 turn_cb = &ast_rtp_turn_rtcp_sock_cb;
1676 conn_type = PJ_TURN_TP_UDP;
1678 conn_type = PJ_TURN_TP_TCP;
1687 rtp->turn_state = PJ_TURN_STATE_NULL;
1691 pj_turn_sock_destroy(*turn_sock);
1693 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
1705 rtp->ioqueue = rtp_ioqueue_thread_get_or_create();
1707 if (!rtp->ioqueue) {
1712 pj_stun_config_init(&stun_config, &
cachingpool.factory, 0, rtp->ioqueue->ioqueue, rtp->ioqueue->timerheap);
1713 if (!stun_software_attribute) {
1714 stun_config.software_name = pj_str(
NULL);
1718 pj_turn_sock_cfg_default(&turn_sock_cfg);
1721 turn_sock_cfg.grp_lock = ice->real_ice->grp_lock;
1727 status = pj_turn_sock_create(&stun_config,
1729 turn_cb, &turn_sock_cfg, instance, turn_sock);
1731 if (
status != PJ_SUCCESS) {
1737 cred.type = PJ_STUN_AUTH_CRED_STATIC;
1738 pj_strset2(&cred.data.static_cred.username, (
char*)username);
1739 cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
1740 pj_strset2(&cred.data.static_cred.data, (
char*)password);
1742 pj_turn_sock_alloc(*turn_sock, pj_cstr(&turn_addr, server), port,
NULL, &cred,
NULL);
1744 ast_debug_ice(2,
"(%p) ICE request TURN %s %s candidate\n", instance,
1754 while (rtp->turn_state < PJ_TURN_STATE_READY) {
1759 if (rtp->turn_state != PJ_TURN_STATE_READY) {
1763 pj_turn_sock_get_info(*turn_sock, &
info);
1765 ast_rtp_ice_add_cand(instance, rtp, component, conn_transport,
1766 PJ_ICE_CAND_TYPE_RELAYED, 65535, &
info.relay_addr, &
info.relay_addr,
1767 &
info.mapped_addr, pj_sockaddr_get_len(&
info.relay_addr));
1781 for (x=0; x<4; x++) {
1784 snprintf(
buf, size,
"%08lx%08lx%08lx%08lx", (
long unsigned)
val[0], (
long unsigned)
val[1], (
long unsigned)
val[2], (
long unsigned)
val[3]);
1790static void ast_rtp_ice_change_components(
struct ast_rtp_instance *instance,
int num_components)
1797 if (!icesupport || !rtp->ice || rtp->ice_num_components == num_components) {
1801 ast_debug_ice(2,
"(%p) ICE change number of components %u -> %u\n", instance,
1802 rtp->ice_num_components, num_components);
1804 rtp->ice_num_components = num_components;
1805 ice_reset_session(instance);
1811 .add_remote_candidate = ast_rtp_ice_add_remote_candidate,
1812 .start = ast_rtp_ice_start,
1813 .stop = ast_rtp_ice_stop,
1814 .get_ufrag = ast_rtp_ice_get_ufrag,
1815 .get_password = ast_rtp_ice_get_password,
1816 .get_local_candidates = ast_rtp_ice_get_local_candidates,
1817 .ice_lite = ast_rtp_ice_lite,
1818 .set_role = ast_rtp_ice_set_role,
1819 .turn_request = ast_rtp_ice_turn_request,
1820 .change_components = ast_rtp_ice_change_components,
1824#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
1825static int dtls_verify_callback(
int preverify_ok, X509_STORE_CTX *ctx)
1831static int dtls_details_initialize(
struct dtls_details *dtls,
SSL_CTX *ssl_ctx,
1834 dtls->dtls_setup = setup;
1836 if (!(dtls->ssl = SSL_new(ssl_ctx))) {
1841 if (!(dtls->read_bio = BIO_new(BIO_s_mem()))) {
1845 BIO_set_mem_eof_return(dtls->read_bio, -1);
1847#ifdef HAVE_OPENSSL_BIO_METHOD
1848 if (!(dtls->write_bio = BIO_new(dtls_bio_methods))) {
1849 ast_log(
LOG_ERROR,
"Failed to allocate memory for outbound SSL traffic\n");
1853 BIO_set_data(dtls->write_bio, instance);
1855 if (!(dtls->write_bio = BIO_new(&dtls_bio_methods))) {
1856 ast_log(
LOG_ERROR,
"Failed to allocate memory for outbound SSL traffic\n");
1859 dtls->write_bio->ptr = instance;
1861 SSL_set_bio(dtls->ssl, dtls->read_bio, dtls->write_bio);
1864 SSL_set_accept_state(dtls->ssl);
1866 SSL_set_connect_state(dtls->ssl);
1873 if (dtls->read_bio) {
1874 BIO_free(dtls->read_bio);
1875 dtls->read_bio =
NULL;
1878 if (dtls->write_bio) {
1879 BIO_free(dtls->write_bio);
1880 dtls->write_bio =
NULL;
1884 SSL_free(dtls->ssl);
1894 if (!rtp->ssl_ctx || !rtp->
rtcp) {
1899 return dtls_details_initialize(&rtp->
rtcp->dtls, rtp->ssl_ctx, rtp->dtls.dtls_setup, instance);
1902static const SSL_METHOD *get_dtls_method(
void)
1904#if OPENSSL_VERSION_NUMBER < 0x10002000L
1905 return DTLSv1_method();
1907 return DTLS_method();
1911struct dtls_cert_info {
1912 EVP_PKEY *private_key;
1916static int apply_dh_params(
SSL_CTX *ctx, BIO *bio)
1920#if OPENSSL_VERSION_NUMBER >= 0x30000000L
1921 EVP_PKEY *dhpkey = PEM_read_bio_Parameters(bio,
NULL);
1922 if (dhpkey && EVP_PKEY_is_a(dhpkey,
"DH")) {
1923 res = SSL_CTX_set0_tmp_dh_pkey(ctx, dhpkey);
1929 EVP_PKEY_free(dhpkey);
1934 res = SSL_CTX_set_tmp_dh(ctx, dh);
1944#if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
1948#ifndef OPENSSL_NO_DH
1950 BIO *bio = BIO_new_file(dtls_cfg->
pvtfile,
"r");
1952 if (apply_dh_params(rtp->ssl_ctx, bio)) {
1953 long options = SSL_OP_CIPHER_SERVER_PREFERENCE |
1954 SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
1956 ast_verb(2,
"DTLS DH initialized, PFS enabled\n");
1963#if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
1965 ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1967 if (SSL_CTX_set_tmp_ecdh(rtp->ssl_ctx, ecdh)) {
1968 #ifndef SSL_CTRL_SET_ECDH_AUTO
1969 #define SSL_CTRL_SET_ECDH_AUTO 94
1972 if (SSL_CTX_ctrl(rtp->ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1,
NULL)) {
1973 ast_verb(2,
"DTLS ECDH initialized (automatic), faster PFS enabled\n");
1975 ast_verb(2,
"DTLS ECDH initialized (secp256r1), faster PFS enabled\n");
1983#if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L)
1985static int create_ephemeral_ec_keypair(EVP_PKEY **keypair)
1987#if OPENSSL_VERSION_NUMBER >= 0x30000000L
1988 *keypair = EVP_EC_gen(SN_X9_62_prime256v1);
1989 return *keypair ? 0 : -1;
1991 EC_KEY *eckey =
NULL;
1994 group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
1999 EC_GROUP_set_asn1_flag(
group, OPENSSL_EC_NAMED_CURVE);
2000 EC_GROUP_set_point_conversion_form(
group, POINT_CONVERSION_UNCOMPRESSED);
2002 eckey = EC_KEY_new();
2007 if (!EC_KEY_set_group(eckey,
group)) {
2011 if (!EC_KEY_generate_key(eckey)) {
2015 *keypair = EVP_PKEY_new();
2020 EVP_PKEY_assign_EC_KEY(*keypair, eckey);
2021 EC_GROUP_free(
group);
2027 EC_GROUP_free(
group);
2034#define SERIAL_RAND_BITS 159
2036static int create_ephemeral_certificate(EVP_PKEY *keypair, X509 **certificate)
2039 BIGNUM *serial =
NULL;
2047 if (!X509_set_version(cert, 2)) {
2052 X509_set_pubkey(cert, keypair);
2055 if (!(serial = BN_new())
2056 || !BN_rand(serial, SERIAL_RAND_BITS, -1, 0)
2057 || !BN_to_ASN1_INTEGER(serial, X509_get_serialNumber(cert))) {
2068#if OPENSSL_VERSION_NUMBER < 0x10100000L
2069 if (!X509_time_adj_ex(X509_get_notBefore(cert), -1, 0,
NULL)
2070 || !X509_time_adj_ex(X509_get_notAfter(cert), 30, 0,
NULL)) {
2074 if (!X509_time_adj_ex(X509_getm_notBefore(cert), -1, 0,
NULL)
2075 || !X509_time_adj_ex(X509_getm_notAfter(cert), 30, 0,
NULL)) {
2081 if (!(
name = X509_get_subject_name(cert))
2082 || !X509_NAME_add_entry_by_NID(
name, NID_commonName, MBSTRING_ASC,
2083 (
unsigned char *)
"asterisk", -1, -1, 0)
2084 || !X509_set_issuer_name(cert,
name)) {
2089 if (!X509_sign(cert, keypair, EVP_sha256())) {
2093 *certificate = cert;
2105 struct dtls_cert_info *cert_info)
2108 cert_info->private_key =
NULL;
2109 cert_info->certificate =
NULL;
2111 if (create_ephemeral_ec_keypair(&cert_info->private_key)) {
2116 if (create_ephemeral_certificate(cert_info->private_key, &cert_info->certificate)) {
2124 X509_free(cert_info->certificate);
2125 EVP_PKEY_free(cert_info->private_key);
2134 struct dtls_cert_info *cert_info)
2136 ast_log(
LOG_ERROR,
"Your version of OpenSSL does not support ECDSA keys\n");
2144 struct dtls_cert_info *cert_info)
2147 BIO *certbio =
NULL;
2148 EVP_PKEY *private_key =
NULL;
2152 fp = fopen(private_key_file,
"r");
2154 ast_log(
LOG_ERROR,
"Failed to read private key from file '%s': %s\n", private_key_file, strerror(
errno));
2158 if (!PEM_read_PrivateKey(fp, &private_key,
NULL,
NULL)) {
2159 ast_log(
LOG_ERROR,
"Failed to read private key from PEM file '%s'\n", private_key_file);
2165 ast_log(
LOG_ERROR,
"Failed to close private key file '%s': %s\n", private_key_file, strerror(
errno));
2169 certbio = BIO_new(BIO_s_file());
2171 ast_log(
LOG_ERROR,
"Failed to allocate memory for certificate fingerprinting on RTP instance '%p'\n",
2176 if (!BIO_read_filename(certbio, dtls_cfg->
certfile)
2177 || !(cert = PEM_read_bio_X509(certbio,
NULL, 0,
NULL))) {
2182 cert_info->private_key = private_key;
2183 cert_info->certificate = cert;
2185 BIO_free_all(certbio);
2191 BIO_free_all(certbio);
2192 EVP_PKEY_free(private_key);
2199 struct dtls_cert_info *cert_info)
2202 return create_certificate_ephemeral(instance, dtls_cfg, cert_info);
2204 return create_certificate_from_file(instance, dtls_cfg, cert_info);
2214 struct dtls_cert_info cert_info = { 0 };
2224 ast_log(
LOG_ERROR,
"SRTP support module is not loaded or available. Try loading res_srtp.so.\n");
2232 rtp->ssl_ctx = SSL_CTX_new(get_dtls_method());
2233 if (!rtp->ssl_ctx) {
2237 SSL_CTX_set_read_ahead(rtp->ssl_ctx, 1);
2239 configure_dhparams(rtp, dtls_cfg);
2241 rtp->dtls_verify = dtls_cfg->
verify;
2245 dtls_verify_callback :
NULL);
2248 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx,
"SRTP_AES128_CM_SHA1_80");
2250 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx,
"SRTP_AES128_CM_SHA1_32");
2252 ast_log(
LOG_ERROR,
"Unsupported suite specified for DTLS-SRTP on RTP instance '%p'\n", instance);
2256 rtp->local_hash = dtls_cfg->
hash;
2258 if (!load_dtls_certificate(instance, dtls_cfg, &cert_info)) {
2260 unsigned int size, i;
2261 unsigned char fingerprint[EVP_MAX_MD_SIZE];
2262 char *local_fingerprint = rtp->local_fingerprint;
2264 if (!SSL_CTX_use_certificate(rtp->ssl_ctx, cert_info.certificate)) {
2265 ast_log(
LOG_ERROR,
"Specified certificate for RTP instance '%p' could not be used\n",
2270 if (!SSL_CTX_use_PrivateKey(rtp->ssl_ctx, cert_info.private_key)
2271 || !SSL_CTX_check_private_key(rtp->ssl_ctx)) {
2272 ast_log(
LOG_ERROR,
"Specified private key for RTP instance '%p' could not be used\n",
2280 type = EVP_sha256();
2282 ast_log(
LOG_ERROR,
"Unsupported fingerprint hash type on RTP instance '%p'\n",
2287 if (!X509_digest(cert_info.certificate,
type, fingerprint, &size) || !size) {
2288 ast_log(
LOG_ERROR,
"Could not produce fingerprint from certificate for RTP instance '%p'\n",
2293 for (i = 0; i < size; i++) {
2294 sprintf(local_fingerprint,
"%02hhX:", fingerprint[i]);
2295 local_fingerprint += 3;
2298 *(local_fingerprint - 1) = 0;
2300 EVP_PKEY_free(cert_info.private_key);
2301 X509_free(cert_info.certificate);
2305 if (!SSL_CTX_set_cipher_list(rtp->ssl_ctx, dtls_cfg->
cipher)) {
2306 ast_log(
LOG_ERROR,
"Invalid cipher specified in cipher list '%s' for RTP instance '%p'\n",
2307 dtls_cfg->
cipher, instance);
2314 ast_log(
LOG_ERROR,
"Invalid certificate authority file '%s' or path '%s' specified for RTP instance '%p'\n",
2320 rtp->rekey = dtls_cfg->
rekey;
2321 rtp->suite = dtls_cfg->
suite;
2323 res = dtls_details_initialize(&rtp->dtls, rtp->ssl_ctx, dtls_cfg->
default_setup, instance);
2325 dtls_setup_rtcp(instance);
2336 return !rtp->ssl_ctx ? 0 : 1;
2343 SSL *ssl = rtp->dtls.ssl;
2347 dtls_srtp_stop_timeout_timer(instance, rtp, 0);
2351 SSL_CTX_free(rtp->ssl_ctx);
2352 rtp->ssl_ctx =
NULL;
2355 if (rtp->dtls.ssl) {
2356 SSL_free(rtp->dtls.ssl);
2357 rtp->dtls.ssl =
NULL;
2362 dtls_srtp_stop_timeout_timer(instance, rtp, 1);
2365 if (rtp->
rtcp->dtls.ssl) {
2366 if (rtp->
rtcp->dtls.ssl != ssl) {
2367 SSL_free(rtp->
rtcp->dtls.ssl);
2379 if (SSL_is_init_finished(rtp->dtls.ssl)) {
2380 SSL_shutdown(rtp->dtls.ssl);
2384 if (rtp->
rtcp && SSL_is_init_finished(rtp->
rtcp->dtls.ssl)) {
2385 SSL_shutdown(rtp->
rtcp->dtls.ssl);
2395 return rtp->dtls.connection;
2403 return rtp->dtls.dtls_setup;
2432 if (old == *dtls_setup) {
2442 SSL_set_connect_state(ssl);
2444 SSL_set_accept_state(ssl);
2455 if (rtp->dtls.ssl) {
2456 dtls_set_setup(&rtp->dtls.dtls_setup, setup, rtp->dtls.ssl);
2459 if (rtp->
rtcp && rtp->
rtcp->dtls.ssl) {
2460 dtls_set_setup(&rtp->
rtcp->dtls.dtls_setup, setup, rtp->
rtcp->dtls.ssl);
2475 rtp->remote_hash = hash;
2477 while ((
value =
strsep(&
tmp,
":")) && (pos != (EVP_MAX_MD_SIZE - 1))) {
2478 sscanf(
value,
"%02hhx", &rtp->remote_fingerprint[pos++]);
2487 return rtp->local_hash;
2491static const char *ast_rtp_dtls_get_fingerprint(
struct ast_rtp_instance *instance)
2495 return rtp->local_fingerprint;
2501 .active = ast_rtp_dtls_active,
2502 .stop = ast_rtp_dtls_stop,
2503 .reset = ast_rtp_dtls_reset,
2504 .get_connection = ast_rtp_dtls_get_connection,
2505 .get_setup = ast_rtp_dtls_get_setup,
2506 .set_setup = ast_rtp_dtls_set_setup,
2507 .set_fingerprint = ast_rtp_dtls_set_fingerprint,
2508 .get_fingerprint_hash = ast_rtp_dtls_get_fingerprint_hash,
2509 .get_fingerprint = ast_rtp_dtls_get_fingerprint,
2514#ifdef TEST_FRAMEWORK
2552 if (rtp && rtp->
rtcp) {
2557static struct ast_rtp_engine_test ast_rtp_test = {
2558 .packets_to_drop = 0,
2561 .recv_buffer_count = get_recv_buffer_count,
2562 .recv_buffer_max = get_recv_buffer_max,
2563 .send_buffer_count = get_send_buffer_count,
2564 .set_schedid = set_rtp_rtcp_schedid,
2594#ifdef HAVE_PJPROJECT
2595 .ice = &ast_rtp_ice,
2597#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2598 .dtls = &ast_rtp_dtls,
2599 .activate = ast_rtp_activate,
2607#ifdef TEST_FRAMEWORK
2608 .test = &ast_rtp_test,
2612#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2614static void dtls_perform_handshake(
struct ast_rtp_instance *instance,
struct dtls_details *
dtls,
int rtcp)
2618 ast_debug_dtls(3,
"(%p) DTLS perform handshake - ssl = %p, setup = %d\n",
2619 rtp, dtls->ssl, dtls->dtls_setup);
2629 SSL_do_handshake(dtls->ssl);
2639 dtls_srtp_start_timeout_timer(instance, rtp,
rtcp);
2643#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2644static void dtls_perform_setup(
struct dtls_details *dtls)
2646 if (!dtls->ssl || !SSL_is_init_finished(dtls->ssl)) {
2650 SSL_clear(dtls->ssl);
2652 SSL_set_accept_state(dtls->ssl);
2654 SSL_set_connect_state(dtls->ssl);
2662#ifdef HAVE_PJPROJECT
2666static void ast_rtp_ice_start_media(pj_ice_sess *ice, pj_status_t
status)
2673 if (
status == PJ_SUCCESS) {
2690#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2692 if (rtp->ice_media_started) {
2698 "(%p) ICE starting media - perform DTLS - (%p)\n", instance, rtp);
2712 dtls_perform_handshake(instance, &rtp->dtls, 0);
2715 dtls_perform_handshake(instance, &rtp->
rtcp->dtls, 1);
2719 rtp->ice_media_started = 1;
2726 ast_verb(4,
"%p -- Strict RTP learning after ICE completion\n", rtp);
2731#ifdef HAVE_PJPROJECT_ON_VALID_ICE_PAIR_CALLBACK
2733static void ast_rtp_on_valid_pair(pj_ice_sess *ice)
2735 ast_debug_ice(2,
"(%p) ICE valid pair, start media\n", ice->user_data);
2736 ast_rtp_ice_start_media(ice, PJ_SUCCESS);
2741static void ast_rtp_on_ice_complete(pj_ice_sess *ice, pj_status_t
status)
2743 ast_debug_ice(2,
"(%p) ICE complete, start media\n", ice->user_data);
2744 ast_rtp_ice_start_media(ice,
status);
2748static void ast_rtp_on_ice_rx_data(pj_ice_sess *ice,
unsigned comp_id,
unsigned transport_id,
void *pkt, pj_size_t size,
const pj_sockaddr_t *src_addr,
unsigned src_addr_len)
2756 rtp->passthrough = 1;
2758 rtp->rtp_passthrough = 1;
2760 rtp->rtcp_passthrough = 1;
2765static pj_status_t ast_rtp_on_ice_tx_pkt(pj_ice_sess *ice,
unsigned comp_id,
unsigned transport_id,
const void *pkt, pj_size_t size,
const pj_sockaddr_t *dst_addr,
unsigned dst_addr_len)
2769 pj_status_t
status = PJ_EINVALIDOP;
2770 pj_ssize_t _size = (pj_ssize_t)size;
2774 status = pj_sock_sendto(rtp->
s, pkt, &_size, 0, dst_addr, dst_addr_len);
2780 status = pj_sock_sendto(rtp->
rtcp->
s, pkt, &_size, 0, dst_addr, dst_addr_len);
2788 if (rtp->turn_rtp) {
2789 status = pj_turn_sock_sendto(rtp->turn_rtp, pkt, size, dst_addr, dst_addr_len);
2793 if (rtp->turn_rtcp) {
2794 status = pj_turn_sock_sendto(rtp->turn_rtcp, pkt, size, dst_addr, dst_addr_len);
2802static pj_ice_sess_cb ast_rtp_ice_sess_cb = {
2803#ifdef HAVE_PJPROJECT_ON_VALID_ICE_PAIR_CALLBACK
2804 .on_valid_pair = ast_rtp_on_valid_pair,
2806 .on_ice_complete = ast_rtp_on_ice_complete,
2807 .on_rx_data = ast_rtp_on_ice_rx_data,
2808 .on_tx_pkt = ast_rtp_on_ice_tx_pkt,
2812static int timer_worker_thread(
void *data)
2814 pj_ioqueue_t *ioqueue;
2816 if (pj_ioqueue_create(pool, 1, &ioqueue) != PJ_SUCCESS) {
2820 while (!timer_terminate) {
2821 const pj_time_val delay = {0, 10};
2823 pj_timer_heap_poll(timer_heap,
NULL);
2824 pj_ioqueue_poll(ioqueue, &delay);
2863#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2868 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->
rtcp->dtls;
2869 struct timeval dtls_timeout;
2871 ast_debug_dtls(3,
"(%p) DTLS srtp - handle timeout - rtcp=%d\n", instance, rtcp);
2872 DTLSv1_handle_timeout(dtls->ssl);
2875 if (!DTLSv1_get_timeout(dtls->ssl, &dtls_timeout)) {
2876 dtls->timeout_timer = -1;
2880 return dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
2884static int dtls_srtp_handle_rtp_timeout(
const void *data)
2890 reschedule = dtls_srtp_handle_timeout(instance, 0);
2900static int dtls_srtp_handle_rtcp_timeout(
const void *
data)
2906 reschedule = dtls_srtp_handle_timeout(instance, 1);
2917 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->
rtcp->dtls;
2918 struct timeval dtls_timeout;
2920 if (DTLSv1_get_timeout(dtls->ssl, &dtls_timeout)) {
2921 int timeout = dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
2927 !rtcp ? dtls_srtp_handle_rtp_timeout : dtls_srtp_handle_rtcp_timeout, instance)) < 0) {
2929 ast_log(
LOG_WARNING,
"Scheduling '%s' DTLS retransmission for RTP instance [%p] failed.\n",
2930 !rtcp ?
"RTP" :
"RTCP", instance);
2932 ast_debug_dtls(3,
"(%p) DTLS srtp - scheduled timeout timer for '%d'\n", instance, timeout);
2940 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->
rtcp->dtls;
2943 ast_debug_dtls(3,
"(%p) DTLS srtp - stopped timeout timer'\n", instance);
2947static int dtls_srtp_renegotiate(
const void *data)
2955 SSL_renegotiate(rtp->dtls.ssl);
2956 SSL_do_handshake(rtp->dtls.ssl);
2958 if (rtp->
rtcp && rtp->
rtcp->dtls.ssl && rtp->
rtcp->dtls.ssl != rtp->dtls.ssl) {
2959 SSL_renegotiate(rtp->
rtcp->dtls.ssl);
2960 SSL_do_handshake(rtp->
rtcp->dtls.ssl);
2974 unsigned char *local_key, *local_salt, *remote_key, *remote_salt;
2977 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->
rtcp->dtls;
2979 ast_debug_dtls(3,
"(%p) DTLS srtp - add local ssrc - rtcp=%d, set_remote_policy=%d'\n",
2980 instance, rtcp, set_remote_policy);
2983 if (!SSL_export_keying_material(dtls->ssl, material,
SRTP_MASTER_LEN * 2,
"EXTRACTOR-dtls_srtp", 19,
NULL, 0, 0)) {
2984 ast_log(
LOG_WARNING,
"Unable to extract SRTP keying material from DTLS-SRTP negotiation on RTP instance '%p'\n",
2991 local_key = material;
2996 remote_key = material;
3007 ast_log(
LOG_WARNING,
"Could not set key/salt information on local policy of '%p' when setting up DTLS-SRTP\n", rtp);
3012 ast_log(
LOG_WARNING,
"Could not set suite to '%u' on local policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
3018 if (set_remote_policy) {
3024 ast_log(
LOG_WARNING,
"Could not set key/salt information on remote policy of '%p' when setting up DTLS-SRTP\n", rtp);
3029 ast_log(
LOG_WARNING,
"Could not set suite to '%u' on remote policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
3037 ast_log(
LOG_WARNING,
"Could not set policies when setting up DTLS-SRTP on '%p'\n", rtp);
3047 if (remote_policy) {
3056 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->
rtcp->dtls;
3059 ast_debug_dtls(3,
"(%p) DTLS setup SRTP rtp=%p'\n", instance, rtp);
3065 if (!(certificate = SSL_get_peer_certificate(dtls->ssl))) {
3066 ast_log(
LOG_WARNING,
"No certificate was provided by the peer on RTP instance '%p'\n", instance);
3071 if (rtp->remote_fingerprint[0]) {
3073 unsigned char fingerprint[EVP_MAX_MD_SIZE];
3079 type = EVP_sha256();
3081 ast_log(
LOG_WARNING,
"Unsupported fingerprint hash type on RTP instance '%p'\n", instance);
3085 if (!X509_digest(certificate,
type, fingerprint, &size) ||
3087 memcmp(fingerprint, rtp->remote_fingerprint, size)) {
3088 X509_free(certificate);
3089 ast_log(
LOG_WARNING,
"Fingerprint provided by remote party does not match that of peer certificate on RTP instance '%p'\n",
3095 X509_free(certificate);
3126 return elem -
value;
3132 return elem ==
value;
3145 version = (packet[0] & 0XC0) >> 6;
3160 m = packet[1] & 0x80;
3161 pt = packet[1] & 0x7F;
3162 if (m && pt >= 64 && pt <= 95) {
3173#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
3176#ifdef HAVE_PJPROJECT
3177 struct ast_sockaddr *loop = rtcp ? &rtp->rtcp_loop : &rtp->rtp_loop;
3179#ifdef TEST_FRAMEWORK
3180 struct ast_rtp_engine_test *
test = ast_rtp_instance_get_test(instance);
3187#ifdef TEST_FRAMEWORK
3188 if (
test &&
test->packets_to_drop > 0) {
3189 test->packets_to_drop--;
3194#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
3197 if ((*
in >= 20) && (*
in <= 63)) {
3198 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->
rtcp->dtls;
3203 ast_log(
LOG_ERROR,
"Received SSL traffic on RTP instance '%p' without an SSL session\n",
3208 ast_debug_dtls(3,
"(%p) DTLS - __rtp_recvfrom rtp=%p - Got SSL packet '%d'\n", instance, rtp, *
in);
3217#ifdef HAVE_PJPROJECT
3219 int pass_src_check = 0;
3233 if (!rtp->ice_media_started) {
3246 for (ix = 0; ix < rtp->ice->real_ice->rcand_cnt; ix++) {
3247 pj_ice_sess_cand *rcand = &rtp->ice->real_ice->rcand[ix];
3254 if (!pass_src_check) {
3255 ast_log(
LOG_WARNING,
"%s: DTLS packet from %s dropped. Source not in ICE active candidate list.\n",
3273 dtls_srtp_stop_timeout_timer(instance, rtp, rtcp);
3279 SSL_set_accept_state(dtls->ssl);
3282 BIO_write(dtls->read_bio,
buf,
len);
3286 if ((
len < 0) && (SSL_get_error(dtls->ssl,
len) == SSL_ERROR_SSL)) {
3287 unsigned long error = ERR_get_error();
3288 ast_log(
LOG_ERROR,
"DTLS failure occurred on RTP instance '%p' due to reason '%s', terminating\n",
3289 instance, ERR_reason_error_string(
error));
3293 if (SSL_is_init_finished(dtls->ssl)) {
3297 if ((res = dtls_srtp_setup(rtp, instance, rtcp))) {
3303 ast_debug_dtls(3,
"(%p) DTLS - __rtp_recvfrom rtp=%p - established'\n", instance, rtp);
3306 dtls_srtp_start_timeout_timer(instance, rtp, rtcp);
3313#ifdef HAVE_PJPROJECT
3323 }
else if (rtp->ice) {
3327 struct ice_wrap *ice;
3329 pj_thread_register_check();
3331 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &combined, &
address);
3337 status = pj_ice_sess_on_rx_pkt(ice->real_ice,
3340 pj_sockaddr_get_len(&
address));
3343 if (
status != PJ_SUCCESS) {
3346 pj_strerror(
status, err_buf,
sizeof(err_buf));
3351 if (!rtp->passthrough) {
3356 if (!rtp->ice_active_remote_candidates && !rtp->ice_proposed_remote_candidates) {
3365 rtp->passthrough = 0;
3401#ifdef HAVE_PJPROJECT
3402 if (transport_rtp->ice) {
3405 struct ice_wrap *ice;
3408 if (rtcp && rtp->
rtcp->
s == rtp->
s) {
3412 pj_thread_register_check();
3415 ice = transport_rtp->ice;
3417 if (instance == transport) {
3420 status = pj_ice_sess_send_data(ice->real_ice, component, temp,
len);
3422 if (instance == transport) {
3425 if (
status == PJ_SUCCESS) {
3463 unsigned int interval;
3476 double last_sum_of_squares = (*std_dev) * (*std_dev) * (*count ?: 1);
3478 if (++(*count) == 0) {
3490 delta1 = new_sample - *mean;
3491 *mean += (delta1 / *count);
3492 delta2 = new_sample - *mean;
3495 *std_dev = sqrt((last_sum_of_squares + (delta1 * delta2)) / *count);
3509 setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums,
sizeof(nochecksums));
3528 memset(&
info->received, 0,
sizeof(
info->received));
3543 if (
seq == (uint16_t) (
info->max_seq + 1)) {
3554 switch (
info->stream_type) {
3564 }
else if (!
info->packets
3581 return info->packets;
3598#ifdef HAVE_PJPROJECT
3644static int stun_address_is_blacklisted(
const struct ast_sockaddr *addr)
3659 unsigned int count = 0;
3660 struct ifaddrs *ifa, *ia;
3663 struct ast_ice_host_candidate *candidate;
3664 int af_inet_ok = 0, af_inet6_ok = 0;
3665 struct sockaddr_in stunaddr_copy;
3670 af_inet_ok = af_inet6_ok = 1;
3675 if (getifaddrs(&ifa) < 0) {
3677 ast_log(
LOG_ERROR,
"(%p) ICE Error obtaining list of local addresses: %s\n",
3678 instance, strerror(
errno));
3680 ast_debug_ice(2,
"(%p) ICE add system candidates\n", instance);
3684 for (ia = ifa; ia && count < PJ_ICE_MAX_CAND; ia = ia->ifa_next) {
3687 if (!ia->ifa_addr || (ia->ifa_flags & IFF_UP) == 0) {
3692 if (ia->ifa_addr->sa_family != AF_INET && ia->ifa_addr->sa_family != AF_INET6) {
3698 if (ia->ifa_addr->sa_family == AF_INET) {
3699 const struct sockaddr_in *sa_in = (
struct sockaddr_in*)ia->ifa_addr;
3707 if ((sa_in->sin_addr.s_addr & htonl(0xFF000000)) == htonl(0x7F000000)) {
3712 if ((sa_in->sin_addr.s_addr & htonl(0xFF000000)) == 0) {
3735 if (!rtp_address_is_ice_blacklisted(&candidate->advertised)) {
3737 pj_sockaddr_set_port(&pjtmp, port);
3738 ast_rtp_ice_add_cand(instance, rtp, component, transport,
3739 PJ_ICE_CAND_TYPE_HOST, 65535, &pjtmp, &pjtmp,
NULL,
3740 pj_sockaddr_get_len(&pjtmp));
3744 if (!candidate->include_local) {
3761 if (rtp_address_is_ice_blacklisted(&
tmp)) {
3766 pj_sockaddr_set_port(&pjtmp, port);
3767 ast_rtp_ice_add_cand(instance, rtp, component, transport,
3768 PJ_ICE_CAND_TYPE_HOST, 65535, &pjtmp, &pjtmp,
NULL,
3769 pj_sockaddr_get_len(&pjtmp));
3776 memcpy(&stunaddr_copy, &stunaddr,
sizeof(stunaddr));
3780 if (stunaddr_copy.sin_addr.s_addr && !stun_address_is_blacklisted(addr) &&
3782 count < PJ_ICE_MAX_CAND) {
3783 struct sockaddr_in
answer;
3787 "(%p) ICE request STUN %s %s candidate\n", instance,
3801 pj_sockaddr
ext, base;
3803 int srflx = 1, baseset = 0;
3806 pj_sockaddr_init(pj_AF_INET(), &
ext, &mapped, ntohs(
answer.sin_port));
3820 if (!pj_sockaddr_cmp(&candidate->
address, &
ext)) {
3828 if (srflx && baseset) {
3829 pj_sockaddr_set_port(&base, port);
3830 ast_rtp_ice_add_cand(instance, rtp, component, transport,
3831 PJ_ICE_CAND_TYPE_SRFLX, 65535, &
ext, &base, &base,
3832 pj_sockaddr_get_len(&
ext));
3838 if (pj_strlen(&turnaddr)) {
3839 ast_rtp_ice_turn_request(instance, component,
AST_TRANSPORT_TCP, pj_strbuf(&turnaddr), turnport,
3840 pj_strbuf(&turnusername), pj_strbuf(&turnpassword));
3871 return (
unsigned int) ms;
3874#ifdef HAVE_PJPROJECT
3892 pj_stun_config stun_config;
3893 pj_str_t ufrag, passwd;
3895 struct ice_wrap *ice_old;
3896 struct ice_wrap *ice;
3897 pj_ice_sess *real_ice =
NULL;
3901 rtp->ice_local_candidates =
NULL;
3907 ast_rtp_ice_stop(instance);
3911 pj_thread_register_check();
3913 pj_stun_config_init(&stun_config, &
cachingpool.factory, 0,
NULL, timer_heap);
3914 if (!stun_software_attribute) {
3915 stun_config.software_name = pj_str(
NULL);
3918 ufrag = pj_str(rtp->local_ufrag);
3919 passwd = pj_str(rtp->local_passwd);
3924 status = pj_ice_sess_create(&stun_config,
NULL, PJ_ICE_SESS_ROLE_UNKNOWN,
3925 rtp->ice_num_components, &ast_rtp_ice_sess_cb, &ufrag, &passwd,
NULL, &real_ice);
3927 if (
status == PJ_SUCCESS) {
3929 real_ice->user_data = instance;
3930 ice->real_ice = real_ice;
3946 if (
replace && rtp->
rtcp && rtp->ice_num_components > 1) {
3947 rtp_add_candidates_to_ice(instance, rtp, &rtp->
rtcp->
us,
3961 ast_rtp_ice_stop(instance);
3969 int x, startplace, i, maxloops;
3978 ast_log(
LOG_WARNING,
"Failed to create a new socket for RTP instance '%p'\n", instance);
3990 for (i = 0; i <= maxloops; i++) {
3994 ast_debug_rtp(1,
"(%p) RTP allocated port %d\n", instance, x);
4006 if (x == startplace || (
errno != EADDRINUSE &&
errno != EACCES)) {
4007 ast_log(
LOG_ERROR,
"Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
4014#ifdef HAVE_PJPROJECT
4023 rtp->ice_num_components = 2;
4024 ast_debug_ice(2,
"(%p) ICE creating session %s (%d)\n", instance,
4035#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
4037 rtp->dtls.timeout_timer = -1;
4045 int saved_rtp_s = rtp->
s;
4046#ifdef HAVE_PJPROJECT
4048 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
4051#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
4052 ast_rtp_dtls_stop(instance);
4063 if (saved_rtp_s != rtp->
rtcp->
s) {
4064 close(rtp->
rtcp->
s);
4069#ifdef HAVE_PJPROJECT
4070 pj_thread_register_check();
4077 if (rtp->turn_rtp) {
4078 rtp->turn_state = PJ_TURN_STATE_NULL;
4082 pj_turn_sock_destroy(rtp->turn_rtp);
4084 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
4087 rtp->turn_rtp =
NULL;
4091 if (rtp->turn_rtcp) {
4092 rtp->turn_state = PJ_TURN_STATE_NULL;
4096 pj_turn_sock_destroy(rtp->turn_rtcp);
4098 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
4101 rtp->turn_rtcp =
NULL;
4104 ast_debug_ice(2,
"(%p) ICE RTP transport deallocating\n", instance);
4106 ast_rtp_ice_stop(instance);
4109 if (rtp->ice_local_candidates) {
4110 ao2_ref(rtp->ice_local_candidates, -1);
4111 rtp->ice_local_candidates =
NULL;
4114 if (rtp->ice_active_remote_candidates) {
4115 ao2_ref(rtp->ice_active_remote_candidates, -1);
4116 rtp->ice_active_remote_candidates =
NULL;
4119 if (rtp->ice_proposed_remote_candidates) {
4120 ao2_ref(rtp->ice_proposed_remote_candidates, -1);
4121 rtp->ice_proposed_remote_candidates =
NULL;
4131 rtp_ioqueue_thread_remove(rtp->ioqueue);
4133 rtp->ioqueue =
NULL;
4149 rtp->
owner = instance;
4192#define SSRC_MAPPING_ELEM_CMP(elem, value) ((elem).instance == (value))
4286 int hdrlen = 12, res = 0, i = 0, payload = -1, sample_rate = -1;
4288 unsigned int *rtpheader = (
unsigned int*)data;
4301 }
else if (
digit ==
'*') {
4303 }
else if (
digit ==
'#') {
4305 }
else if ((
digit >=
'A') && (
digit <=
'D')) {
4307 }
else if ((
digit >=
'a') && (
digit <=
'd')) {
4317 if (payload_format) {
4325 if (sample_rate != -1) {
4329 if (payload == -1 ||
4340 if (payload == -1 || sample_rate == -1) {
4345 if (payload == -1) {
4350 ast_debug(1,
"Sending digit '%d' at rate %d with payload %d\n",
digit, sample_rate, payload);
4359 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->
seqno));
4361 rtpheader[2] = htonl(rtp->
ssrc);
4364 for (i = 0; i < 2; i++) {
4368 res =
rtp_sendto(instance, (
void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
4375 ast_verbose(
"Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
4377 ice ?
" (via ICE)" :
"",
4382 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->
seqno));
4398 int hdrlen = 12, res = 0;
4400 unsigned int *rtpheader = (
unsigned int*)data;
4413 rtpheader[2] = htonl(rtp->
ssrc);
4417 res =
rtp_sendto(instance, (
void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
4425 ast_verbose(
"Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
4427 ice ?
" (via ICE)" :
"",
4444 int hdrlen = 12, res = -1, i = 0;
4446 unsigned int *rtpheader = (
unsigned int*)data;
4447 unsigned int measured_samples;
4459 }
else if (
digit ==
'*') {
4461 }
else if (
digit ==
'#') {
4463 }
else if ((
digit >=
'A') && (
digit <=
'D')) {
4465 }
else if ((
digit >=
'a') && (
digit <=
'd')) {
4475 ast_debug_rtp(2,
"(%p) RTP adjusting final end duration from %d to %u\n",
4482 rtpheader[2] = htonl(rtp->
ssrc);
4484 rtpheader[3] |= htonl((1 << 23));
4487 for (i = 0; i < 3; i++) {
4492 res =
rtp_sendto(instance, (
void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
4501 ast_verbose(
"Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
4503 ice ?
" (via ICE)" :
"",
4542 ast_debug_rtp(3,
"(%p) RTP setting the marker bit due to a source update\n", instance);
4560 ast_debug_rtp(3,
"(%p) RTP changing ssrc from %u to %u due to a source change\n",
4561 instance,
rtp->ssrc, ssrc);
4564 ast_debug_rtp(3,
"(%p) RTP changing ssrc for SRTP from %u to %u\n",
4565 instance,
rtp->ssrc, ssrc);
4567 if (rtcp_srtp != srtp) {
4575 rtp->expectedrxseqno = -1;
4580static void timeval2ntp(
struct timeval tv,
unsigned int *msw,
unsigned int *lsw)
4582 unsigned int sec, usec, frac;
4583 sec = tv.tv_sec + 2208988800u;
4604 frac = ((((usec << 12) / 125) << 7) / 125) << 7;
4609static void ntp2timeval(
unsigned int msw,
unsigned int lsw,
struct timeval *tv)
4611 tv->tv_sec = msw - 2208988800u;
4613 tv->tv_usec = ((((lsw >> 7) * 125) >> 7) * 125) >> 12;
4617 unsigned int *lost_packets,
4620 unsigned int extended_seq_no;
4621 unsigned int expected_packets;
4622 unsigned int expected_interval;
4623 unsigned int received_interval;
4627 extended_seq_no =
rtp->cycles +
rtp->lastrxseqno;
4628 expected_packets = extended_seq_no -
rtp->seedrxseqno + 1;
4629 if (
rtp->rxcount > expected_packets) {
4630 expected_packets +=
rtp->rxcount - expected_packets;
4632 *lost_packets = expected_packets -
rtp->rxcount;
4633 expected_interval = expected_packets -
rtp->rtcp->expected_prior;
4634 received_interval =
rtp->rxcount -
rtp->rtcp->received_prior;
4635 if (received_interval > expected_interval) {
4641 expected_interval = received_interval;
4643 lost_interval = expected_interval - received_interval;
4644 if (expected_interval == 0 || lost_interval <= 0) {
4647 *fraction_lost = (lost_interval << 8) / expected_interval;
4651 rtp->rtcp->received_prior =
rtp->rxcount;
4652 rtp->rtcp->expected_prior = expected_packets;
4660 if (lost_interval <= 0) {
4661 rtp->rtcp->rxlost = 0;
4663 rtp->rtcp->rxlost = lost_interval;
4665 if (
rtp->rtcp->rxlost_count == 0) {
4666 rtp->rtcp->minrxlost =
rtp->rtcp->rxlost;
4668 if (lost_interval && lost_interval < rtp->rtcp->minrxlost) {
4669 rtp->rtcp->minrxlost =
rtp->rtcp->rxlost;
4671 if (lost_interval >
rtp->rtcp->maxrxlost) {
4672 rtp->rtcp->maxrxlost =
rtp->rtcp->rxlost;
4676 &
rtp->rtcp->stdev_rxlost, &
rtp->rtcp->rxlost_count);
4685 unsigned int now_lsw;
4686 unsigned int now_msw;
4687 unsigned int lost_packets;
4689 struct timeval dlsr = { 0, };
4692 if (!rtp || !rtp->
rtcp) {
4715 gettimeofday(&now,
NULL);
4727 report_block =
ast_calloc(1,
sizeof(*report_block));
4728 if (!report_block) {
4742 report_block->
dlsr = (((
dlsr.tv_sec * 1000) + (
dlsr.tv_usec / 1000)) * 65536) / 1000;
4779 if (!rtp || !rtp->
rtcp) {
4802 ast_verbose(
"* Sent RTCP %s to %s%s\n", sr ?
"SR" :
"RR",
4823 ast_verbose(
" DLSR: %4.4f (sec)\n\n", (
double)(report_block->
dlsr / 65536.0));
4833 rtcp_report, message_blob);
4843 uint16_t sdes_packet_len_bytes;
4844 uint16_t sdes_packet_len_rounded;
4846 if (!rtp || !rtp->
rtcp) {
4858 sdes_packet_len_bytes =
4867 sdes_packet_len_rounded = (sdes_packet_len_bytes + 3) & ~0x3;
4871 rtcpheader[8] = 0x01;
4886 len += (sdes_packet_len_rounded - sdes_packet_len_bytes);
4909 if (res == 0 || res == 1) {
4910 ast_debug_rtcp(1,
"(%p) RTCP failed to generate %s report!\n", instance, sr ?
"SR" :
"RR");
4918 if (res == 0 || res == 1) {
4919 ast_debug_rtcp(1,
"(%p) RTCP failed to generate SDES!\n", instance);
4923 return packet_len + res;
4932 unsigned int fci = 0;
4933 size_t remaining_missing_seqno;
4935 if (!rtp || !rtp->
rtcp) {