PJSIP FAX: Fix T.38 automatic reject timer NULL channel pointer dereferences.
[asterisk/asterisk.git] / res / res_rtp_asterisk.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2008, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file
21  *
22  * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
23  *
24  * \author Mark Spencer <markster@digium.com>
25  *
26  * \note RTP is defined in RFC 3550.
27  *
28  * \ingroup rtp_engines
29  */
30
31 /*** MODULEINFO
32         <use type="external">pjproject</use>
33         <support_level>core</support_level>
34  ***/
35
36 #include "asterisk.h"
37
38 ASTERISK_REGISTER_FILE()
39
40 #include <sys/time.h>
41 #include <signal.h>
42 #include <fcntl.h>
43
44 #ifdef HAVE_OPENSSL_SRTP
45 #include <openssl/ssl.h>
46 #include <openssl/err.h>
47 #include <openssl/bio.h>
48 #endif
49
50 #ifdef HAVE_PJPROJECT
51 #include <pjlib.h>
52 #include <pjlib-util.h>
53 #include <pjnath.h>
54 #endif
55
56 #include "asterisk/stun.h"
57 #include "asterisk/pbx.h"
58 #include "asterisk/frame.h"
59 #include "asterisk/format_cache.h"
60 #include "asterisk/channel.h"
61 #include "asterisk/acl.h"
62 #include "asterisk/config.h"
63 #include "asterisk/lock.h"
64 #include "asterisk/utils.h"
65 #include "asterisk/cli.h"
66 #include "asterisk/manager.h"
67 #include "asterisk/unaligned.h"
68 #include "asterisk/module.h"
69 #include "asterisk/rtp_engine.h"
70 #include "asterisk/smoother.h"
71 #include "asterisk/test.h"
72
73 #define MAX_TIMESTAMP_SKEW      640
74
75 #define RTP_SEQ_MOD     (1<<16) /*!< A sequence number can't be more than 16 bits */
76 #define RTCP_DEFAULT_INTERVALMS   5000  /*!< Default milli-seconds between RTCP reports we send */
77 #define RTCP_MIN_INTERVALMS       500   /*!< Min milli-seconds between RTCP reports we send */
78 #define RTCP_MAX_INTERVALMS       60000 /*!< Max milli-seconds between RTCP reports we send */
79
80 #define DEFAULT_RTP_START 5000 /*!< Default port number to start allocating RTP ports from */
81 #define DEFAULT_RTP_END 31000  /*!< Default maximum port number to end allocating RTP ports at */
82
83 #define MINIMUM_RTP_PORT 1024 /*!< Minimum port number to accept */
84 #define MAXIMUM_RTP_PORT 65535 /*!< Maximum port number to accept */
85
86 #define DEFAULT_TURN_PORT 3478
87
88 #define TURN_STATE_WAIT_TIME 2000
89
90 #define RTCP_PT_FUR     192
91 #define RTCP_PT_SR      AST_RTP_RTCP_SR
92 #define RTCP_PT_RR      AST_RTP_RTCP_RR
93 #define RTCP_PT_SDES    202
94 #define RTCP_PT_BYE     203
95 #define RTCP_PT_APP     204
96 /* VP8: RTCP Feedback */
97 #define RTCP_PT_PSFB    206
98
99 #define RTP_MTU         1200
100 #define DTMF_SAMPLE_RATE_MS    8 /*!< DTMF samples per millisecond */
101
102 #define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000))      /*!< samples */
103
104 #define ZFONE_PROFILE_ID 0x505a
105
106 #define DEFAULT_LEARNING_MIN_SEQUENTIAL 4
107
108 #define SRTP_MASTER_KEY_LEN 16
109 #define SRTP_MASTER_SALT_LEN 14
110 #define SRTP_MASTER_LEN (SRTP_MASTER_KEY_LEN + SRTP_MASTER_SALT_LEN)
111
112 enum strict_rtp_state {
113         STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
114         STRICT_RTP_LEARN,    /*! Accept next packet as source */
115         STRICT_RTP_CLOSED,   /*! Drop all RTP packets not coming from source that was learned */
116 };
117
118 #define DEFAULT_STRICT_RTP STRICT_RTP_CLOSED
119 #define DEFAULT_ICESUPPORT 1
120
121 extern struct ast_srtp_res *res_srtp;
122 extern struct ast_srtp_policy_res *res_srtp_policy;
123
124 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
125
126 static int rtpstart = DEFAULT_RTP_START;                        /*!< First port for RTP sessions (set in rtp.conf) */
127 static int rtpend = DEFAULT_RTP_END;                    /*!< Last port for RTP sessions (set in rtp.conf) */
128 static int rtpdebug;                    /*!< Are we debugging? */
129 static int rtcpdebug;                   /*!< Are we debugging RTCP? */
130 static int rtcpstats;                   /*!< Are we debugging RTCP? */
131 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
132 static struct ast_sockaddr rtpdebugaddr;        /*!< Debug packets to/from this host */
133 static struct ast_sockaddr rtcpdebugaddr;       /*!< Debug RTCP packets to/from this host */
134 static int rtpdebugport;                /*< Debug only RTP packets from IP or IP+Port if port is > 0 */
135 static int rtcpdebugport;               /*< Debug only RTCP packets from IP or IP+Port if port is > 0 */
136 #ifdef SO_NO_CHECK
137 static int nochecksums;
138 #endif
139 static int strictrtp = DEFAULT_STRICT_RTP; /*< Only accept RTP frames from a defined source. If we receive an indication of a changing source, enter learning mode. */
140 static int learning_min_sequential = DEFAULT_LEARNING_MIN_SEQUENTIAL; /*< Number of sequential RTP frames needed from a single source during learning mode to accept new source. */
141 #ifdef HAVE_PJPROJECT
142 static int icesupport = DEFAULT_ICESUPPORT;
143 static struct sockaddr_in stunaddr;
144 static pj_str_t turnaddr;
145 static int turnport = DEFAULT_TURN_PORT;
146 static pj_str_t turnusername;
147 static pj_str_t turnpassword;
148
149 /*! \brief Pool factory used by pjlib to allocate memory. */
150 static pj_caching_pool cachingpool;
151
152 /*! \brief Global memory pool for configuration and timers */
153 static pj_pool_t *pool;
154
155 /*! \brief Global timer heap */
156 static pj_timer_heap_t *timer_heap;
157
158 /*! \brief Thread executing the timer heap */
159 static pj_thread_t *timer_thread;
160
161 /*! \brief Used to tell the timer thread to terminate */
162 static int timer_terminate;
163
164 /*! \brief Structure which contains ioqueue thread information */
165 struct ast_rtp_ioqueue_thread {
166         /*! \brief Pool used by the thread */
167         pj_pool_t *pool;
168         /*! \brief The thread handling the queue and timer heap */
169         pj_thread_t *thread;
170         /*! \brief Ioqueue which polls on sockets */
171         pj_ioqueue_t *ioqueue;
172         /*! \brief Timer heap for scheduled items */
173         pj_timer_heap_t *timerheap;
174         /*! \brief Termination request */
175         int terminate;
176         /*! \brief Current number of descriptors being waited on */
177         unsigned int count;
178         /*! \brief Linked list information */
179         AST_LIST_ENTRY(ast_rtp_ioqueue_thread) next;
180 };
181
182 /*! \brief List of ioqueue threads */
183 static AST_LIST_HEAD_STATIC(ioqueues, ast_rtp_ioqueue_thread);
184
185 #endif
186
187 #define FLAG_3389_WARNING               (1 << 0)
188 #define FLAG_NAT_ACTIVE                 (3 << 1)
189 #define FLAG_NAT_INACTIVE               (0 << 1)
190 #define FLAG_NAT_INACTIVE_NOWARN        (1 << 1)
191 #define FLAG_NEED_MARKER_BIT            (1 << 3)
192 #define FLAG_DTMF_COMPENSATE            (1 << 4)
193
194 #define TRANSPORT_SOCKET_RTP 0
195 #define TRANSPORT_SOCKET_RTCP 1
196 #define TRANSPORT_TURN_RTP 2
197 #define TRANSPORT_TURN_RTCP 3
198
199 /*! \brief RTP learning mode tracking information */
200 struct rtp_learning_info {
201         int max_seq;    /*!< The highest sequence number received */
202         int packets;    /*!< The number of remaining packets before the source is accepted */
203 };
204
205 #ifdef HAVE_OPENSSL_SRTP
206 struct dtls_details {
207         SSL *ssl;         /*!< SSL session */
208         BIO *read_bio;    /*!< Memory buffer for reading */
209         BIO *write_bio;   /*!< Memory buffer for writing */
210         enum ast_rtp_dtls_setup dtls_setup; /*!< Current setup state */
211         enum ast_rtp_dtls_connection connection; /*!< Whether this is a new or existing connection */
212 };
213 #endif
214
215 /*! \brief RTP session description */
216 struct ast_rtp {
217         int s;
218         struct ast_frame f;
219         unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
220         unsigned int ssrc;              /*!< Synchronization source, RFC 3550, page 10. */
221         unsigned int themssrc;          /*!< Their SSRC */
222         unsigned int rxssrc;
223         unsigned int lastts;
224         unsigned int lastrxts;
225         unsigned int lastividtimestamp;
226         unsigned int lastovidtimestamp;
227         unsigned int lastitexttimestamp;
228         unsigned int lastotexttimestamp;
229         unsigned int lasteventseqn;
230         int lastrxseqno;                /*!< Last received sequence number */
231         unsigned short seedrxseqno;     /*!< What sequence number did they start with?*/
232         unsigned int seedrxts;          /*!< What RTP timestamp did they start with? */
233         unsigned int rxcount;           /*!< How many packets have we received? */
234         unsigned int rxoctetcount;      /*!< How many octets have we received? should be rxcount *160*/
235         unsigned int txcount;           /*!< How many packets have we sent? */
236         unsigned int txoctetcount;      /*!< How many octets have we sent? (txcount*160)*/
237         unsigned int cycles;            /*!< Shifted count of sequence number cycles */
238         double rxjitter;                /*!< Interarrival jitter at the moment in seconds */
239         double rxtransit;               /*!< Relative transit time for previous packet */
240         struct ast_format *lasttxformat;
241         struct ast_format *lastrxformat;
242
243         int rtptimeout;                 /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
244         int rtpholdtimeout;             /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
245         int rtpkeepalive;               /*!< Send RTP comfort noice packets for keepalive */
246
247         /* DTMF Reception Variables */
248         char resp;                        /*!< The current digit being processed */
249         unsigned int last_seqno;          /*!< The last known sequence number for any DTMF packet */
250         unsigned int last_end_timestamp;  /*!< The last known timestamp received from an END packet */
251         unsigned int dtmf_duration;       /*!< Total duration in samples since the digit start event */
252         unsigned int dtmf_timeout;        /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
253         unsigned int dtmfsamples;
254         enum ast_rtp_dtmf_mode dtmfmode;  /*!< The current DTMF mode of the RTP stream */
255         /* DTMF Transmission Variables */
256         unsigned int lastdigitts;
257         char sending_digit;     /*!< boolean - are we sending digits */
258         char send_digit;        /*!< digit we are sending */
259         int send_payload;
260         int send_duration;
261         unsigned int flags;
262         struct timeval rxcore;
263         struct timeval txcore;
264         double drxcore;                 /*!< The double representation of the first received packet */
265         struct timeval lastrx;          /*!< timeval when we last received a packet */
266         struct timeval dtmfmute;
267         struct ast_smoother *smoother;
268         int *ioid;
269         unsigned short seqno;           /*!< Sequence number, RFC 3550, page 13. */
270         unsigned short rxseqno;
271         struct ast_sched_context *sched;
272         struct io_context *io;
273         void *data;
274         struct ast_rtcp *rtcp;
275         struct ast_rtp *bridged;        /*!< Who we are Packet bridged to */
276
277         enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
278         struct ast_sockaddr strict_rtp_address;  /*!< Remote address information for strict RTP purposes */
279
280         /*
281          * Learning mode values based on pjmedia's probation mode.  Many of these values are redundant to the above,
282          * but these are in place to keep learning mode sequence values sealed from their normal counterparts.
283          */
284         struct rtp_learning_info rtp_source_learn;      /* Learning mode track for the expected RTP source */
285         struct rtp_learning_info alt_source_learn;      /* Learning mode tracking for a new RTP source after one has been chosen */
286
287         struct rtp_red *red;
288
289         ast_mutex_t lock;           /*!< Lock for synchronization purposes */
290         ast_cond_t cond;            /*!< Condition for signaling */
291
292 #ifdef HAVE_PJPROJECT
293         pj_ice_sess *ice;           /*!< ICE session */
294         pj_turn_sock *turn_rtp;     /*!< RTP TURN relay */
295         pj_turn_sock *turn_rtcp;    /*!< RTCP TURN relay */
296         pj_turn_state_t turn_state; /*!< Current state of the TURN relay session */
297         unsigned int passthrough:1; /*!< Bit to indicate that the received packet should be passed through */
298         unsigned int rtp_passthrough:1; /*!< Bit to indicate that TURN RTP should be passed through */
299         unsigned int rtcp_passthrough:1; /*!< Bit to indicate that TURN RTCP should be passed through */
300         unsigned int ice_port;      /*!< Port that ICE was started with if it was previously started */
301         struct ast_sockaddr rtp_loop; /*!< Loopback address for forwarding RTP from TURN */
302         struct ast_sockaddr rtcp_loop; /*!< Loopback address for forwarding RTCP from TURN */
303
304         struct ast_rtp_ioqueue_thread *ioqueue; /*!< The ioqueue thread handling us */
305
306         char remote_ufrag[256];  /*!< The remote ICE username */
307         char remote_passwd[256]; /*!< The remote ICE password */
308
309         char local_ufrag[256];  /*!< The local ICE username */
310         char local_passwd[256]; /*!< The local ICE password */
311
312         struct ao2_container *ice_local_candidates;           /*!< The local ICE candidates */
313         struct ao2_container *ice_active_remote_candidates;   /*!< The remote ICE candidates */
314         struct ao2_container *ice_proposed_remote_candidates; /*!< Incoming remote ICE candidates for new session */
315         struct ast_sockaddr ice_original_rtp_addr;            /*!< rtp address that ICE started on first session */
316 #endif
317
318 #ifdef HAVE_OPENSSL_SRTP
319         SSL_CTX *ssl_ctx; /*!< SSL context */
320         ast_mutex_t dtls_timer_lock;           /*!< Lock for synchronization purposes */
321         enum ast_rtp_dtls_verify dtls_verify; /*!< What to verify */
322         enum ast_srtp_suite suite;   /*!< SRTP crypto suite */
323         enum ast_rtp_dtls_hash local_hash; /*!< Local hash used for the fingerprint */
324         char local_fingerprint[160]; /*!< Fingerprint of our certificate */
325         enum ast_rtp_dtls_hash remote_hash; /*!< Remote hash used for the fingerprint */
326         unsigned char remote_fingerprint[EVP_MAX_MD_SIZE]; /*!< Fingerprint of the peer certificate */
327         unsigned int rekey; /*!< Interval at which to renegotiate and rekey */
328         int rekeyid; /*!< Scheduled item id for rekeying */
329         int dtlstimerid; /*!< Scheduled item id for DTLS retransmission for RTP */
330         struct dtls_details dtls; /*!< DTLS state information */
331 #endif
332 };
333
334 /*!
335  * \brief Structure defining an RTCP session.
336  *
337  * The concept "RTCP session" is not defined in RFC 3550, but since
338  * this structure is analogous to ast_rtp, which tracks a RTP session,
339  * it is logical to think of this as a RTCP session.
340  *
341  * RTCP packet is defined on page 9 of RFC 3550.
342  *
343  */
344 struct ast_rtcp {
345         int rtcp_info;
346         int s;                          /*!< Socket */
347         struct ast_sockaddr us;         /*!< Socket representation of the local endpoint. */
348         struct ast_sockaddr them;       /*!< Socket representation of the remote endpoint. */
349         unsigned int soc;               /*!< What they told us */
350         unsigned int spc;               /*!< What they told us */
351         unsigned int themrxlsr;         /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
352         struct timeval rxlsr;           /*!< Time when we got their last SR */
353         struct timeval txlsr;           /*!< Time when we sent or last SR*/
354         unsigned int expected_prior;    /*!< no. packets in previous interval */
355         unsigned int received_prior;    /*!< no. packets received in previous interval */
356         int schedid;                    /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
357         unsigned int rr_count;          /*!< number of RRs we've sent, not including report blocks in SR's */
358         unsigned int sr_count;          /*!< number of SRs we've sent */
359         unsigned int lastsrtxcount;     /*!< Transmit packet count when last SR sent */
360         double accumulated_transit;     /*!< accumulated a-dlsr-lsr */
361         double rtt;                     /*!< Last reported rtt */
362         unsigned int reported_jitter;   /*!< The contents of their last jitter entry in the RR */
363         unsigned int reported_lost;     /*!< Reported lost packets in their RR */
364
365         double reported_maxjitter;
366         double reported_minjitter;
367         double reported_normdev_jitter;
368         double reported_stdev_jitter;
369         unsigned int reported_jitter_count;
370
371         double reported_maxlost;
372         double reported_minlost;
373         double reported_normdev_lost;
374         double reported_stdev_lost;
375
376         double rxlost;
377         double maxrxlost;
378         double minrxlost;
379         double normdev_rxlost;
380         double stdev_rxlost;
381         unsigned int rxlost_count;
382
383         double maxrxjitter;
384         double minrxjitter;
385         double normdev_rxjitter;
386         double stdev_rxjitter;
387         unsigned int rxjitter_count;
388         double maxrtt;
389         double minrtt;
390         double normdevrtt;
391         double stdevrtt;
392         unsigned int rtt_count;
393
394         /* VP8: sequence number for the RTCP FIR FCI */
395         int firseq;
396
397 #ifdef HAVE_OPENSSL_SRTP
398         struct dtls_details dtls; /*!< DTLS state information */
399 #endif
400 };
401
402 struct rtp_red {
403         struct ast_frame t140;  /*!< Primary data  */
404         struct ast_frame t140red;   /*!< Redundant t140*/
405         unsigned char pt[AST_RED_MAX_GENERATION];  /*!< Payload types for redundancy data */
406         unsigned char ts[AST_RED_MAX_GENERATION]; /*!< Time stamps */
407         unsigned char len[AST_RED_MAX_GENERATION]; /*!< length of each generation */
408         int num_gen; /*!< Number of generations */
409         int schedid; /*!< Timer id */
410         int ti; /*!< How long to buffer data before send */
411         unsigned char t140red_data[64000];
412         unsigned char buf_data[64000]; /*!< buffered primary data */
413         int hdrlen;
414         long int prev_ts;
415 };
416
417 AST_LIST_HEAD_NOLOCK(frame_list, ast_frame);
418
419 /* Forward Declarations */
420 static int ast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data);
421 static int ast_rtp_destroy(struct ast_rtp_instance *instance);
422 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
423 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
424 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration);
425 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode);
426 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance);
427 static void ast_rtp_update_source(struct ast_rtp_instance *instance);
428 static void ast_rtp_change_source(struct ast_rtp_instance *instance);
429 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
430 static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
431 static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
432 static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
433 static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
434 static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
435 static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
436 static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
437 static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
438 static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
439 static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username);
440 static void ast_rtp_stop(struct ast_rtp_instance *instance);
441 static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char* desc);
442 static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level);
443
444 #ifdef HAVE_OPENSSL_SRTP
445 static int ast_rtp_activate(struct ast_rtp_instance *instance);
446 static void dtls_srtp_check_pending(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp);
447 #endif
448
449 static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *ice, int use_srtp);
450
451 #ifdef HAVE_PJPROJECT
452 /*! \brief Helper function which updates an ast_sockaddr with the candidate used for the component */
453 static void update_address_with_ice_candidate(struct ast_rtp *rtp, enum ast_rtp_ice_component_type component,
454         struct ast_sockaddr *cand_address)
455 {
456         char address[PJ_INET6_ADDRSTRLEN];
457
458         if (!rtp->ice || (component < 1) || !rtp->ice->comp[component - 1].valid_check) {
459                 return;
460         }
461
462         ast_sockaddr_parse(cand_address, pj_sockaddr_print(&rtp->ice->comp[component - 1].valid_check->rcand->addr, address, sizeof(address), 0), 0);
463         ast_sockaddr_set_port(cand_address, pj_sockaddr_get_port(&rtp->ice->comp[component - 1].valid_check->rcand->addr));
464 }
465
466 /*! \brief Destructor for locally created ICE candidates */
467 static void ast_rtp_ice_candidate_destroy(void *obj)
468 {
469         struct ast_rtp_engine_ice_candidate *candidate = obj;
470
471         if (candidate->foundation) {
472                 ast_free(candidate->foundation);
473         }
474
475         if (candidate->transport) {
476                 ast_free(candidate->transport);
477         }
478 }
479
480 static void ast_rtp_ice_set_authentication(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
481 {
482         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
483
484         if (!ast_strlen_zero(ufrag)) {
485                 ast_copy_string(rtp->remote_ufrag, ufrag, sizeof(rtp->remote_ufrag));
486         }
487
488         if (!ast_strlen_zero(password)) {
489                 ast_copy_string(rtp->remote_passwd, password, sizeof(rtp->remote_passwd));
490         }
491 }
492
493 static int ice_candidate_cmp(void *obj, void *arg, int flags)
494 {
495         struct ast_rtp_engine_ice_candidate *candidate1 = obj, *candidate2 = arg;
496
497         if (strcmp(candidate1->foundation, candidate2->foundation) ||
498                         candidate1->id != candidate2->id ||
499                         ast_sockaddr_cmp(&candidate1->address, &candidate2->address) ||
500                         candidate1->type != candidate1->type) {
501                 return 0;
502         }
503
504         return CMP_MATCH | CMP_STOP;
505 }
506
507 static void ast_rtp_ice_add_remote_candidate(struct ast_rtp_instance *instance, const struct ast_rtp_engine_ice_candidate *candidate)
508 {
509         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
510         struct ast_rtp_engine_ice_candidate *remote_candidate;
511
512         /* ICE sessions only support UDP candidates */
513         if (strcasecmp(candidate->transport, "udp")) {
514                 return;
515         }
516
517         if (!rtp->ice_proposed_remote_candidates &&
518                         !(rtp->ice_proposed_remote_candidates = ao2_container_alloc(1, NULL, ice_candidate_cmp))) {
519                 return;
520         }
521
522         /* If this is going to exceed the maximum number of ICE candidates don't even add it */
523         if (ao2_container_count(rtp->ice_proposed_remote_candidates) == PJ_ICE_MAX_CAND) {
524                 return;
525         }
526
527         if (!(remote_candidate = ao2_alloc(sizeof(*remote_candidate), ast_rtp_ice_candidate_destroy))) {
528                 return;
529         }
530
531         remote_candidate->foundation = ast_strdup(candidate->foundation);
532         remote_candidate->id = candidate->id;
533         remote_candidate->transport = ast_strdup(candidate->transport);
534         remote_candidate->priority = candidate->priority;
535         ast_sockaddr_copy(&remote_candidate->address, &candidate->address);
536         ast_sockaddr_copy(&remote_candidate->relay_address, &candidate->relay_address);
537         remote_candidate->type = candidate->type;
538
539         ao2_link(rtp->ice_proposed_remote_candidates, remote_candidate);
540         ao2_ref(remote_candidate, -1);
541 }
542
543 AST_THREADSTORAGE(pj_thread_storage);
544
545 /*! \brief Function used to check if the calling thread is registered with pjlib. If it is not it will be registered. */
546 static void pj_thread_register_check(void)
547 {
548         pj_thread_desc *desc;
549         pj_thread_t *thread;
550
551         if (pj_thread_is_registered() == PJ_TRUE) {
552                 return;
553         }
554
555         desc = ast_threadstorage_get(&pj_thread_storage, sizeof(pj_thread_desc));
556         if (!desc) {
557                 ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage. Expect awful things to occur\n");
558                 return;
559         }
560         pj_bzero(*desc, sizeof(*desc));
561
562         if (pj_thread_register("Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
563                 ast_log(LOG_ERROR, "Coudln't register thread with PJLIB.\n");
564         }
565         return;
566 }
567
568 static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
569         int port, int replace);
570
571 static void ast_rtp_ice_stop(struct ast_rtp_instance *instance)
572 {
573         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
574
575         if (!rtp->ice) {
576                 return;
577         }
578
579         pj_thread_register_check();
580
581         pj_ice_sess_destroy(rtp->ice);
582         rtp->ice = NULL;
583 }
584
585 static int ice_reset_session(struct ast_rtp_instance *instance)
586 {
587         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
588         pj_ice_sess_role role = rtp->ice->role;
589         int res;
590
591         if (!rtp->ice->is_nominating && !rtp->ice->is_complete) {
592                 return 0;
593         }
594
595         ast_rtp_ice_stop(instance);
596
597         res = ice_create(instance, &rtp->ice_original_rtp_addr, rtp->ice_port, 1);
598         if (!res) {
599                 /* Preserve the role that the old ICE session used */
600                 pj_ice_sess_change_role(rtp->ice, role);
601         }
602
603         return res;
604 }
605
606 static int ice_candidates_compare(struct ao2_container *left, struct ao2_container *right)
607 {
608         struct ao2_iterator i;
609         struct ast_rtp_engine_ice_candidate *right_candidate;
610
611         if (ao2_container_count(left) != ao2_container_count(right)) {
612                 return -1;
613         }
614
615         i = ao2_iterator_init(right, 0);
616         while ((right_candidate = ao2_iterator_next(&i))) {
617                 struct ast_rtp_engine_ice_candidate *left_candidate = ao2_find(left, right_candidate, OBJ_POINTER);
618
619                 if (!left_candidate) {
620                         ao2_ref(right_candidate, -1);
621                         ao2_iterator_destroy(&i);
622                         return -1;
623                 }
624
625                 ao2_ref(left_candidate, -1);
626                 ao2_ref(right_candidate, -1);
627         }
628         ao2_iterator_destroy(&i);
629
630         return 0;
631 }
632
633 static void ast_rtp_ice_start(struct ast_rtp_instance *instance)
634 {
635         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
636         pj_str_t ufrag = pj_str(rtp->remote_ufrag), passwd = pj_str(rtp->remote_passwd);
637         pj_ice_sess_cand candidates[PJ_ICE_MAX_CAND];
638         struct ao2_iterator i;
639         struct ast_rtp_engine_ice_candidate *candidate;
640         int cand_cnt = 0, has_rtp = 0, has_rtcp = 0;
641
642         if (!rtp->ice || !rtp->ice_proposed_remote_candidates) {
643                 return;
644         }
645
646         /* Check for equivalence in the lists */
647         if (rtp->ice_active_remote_candidates &&
648                         !ice_candidates_compare(rtp->ice_proposed_remote_candidates, rtp->ice_active_remote_candidates)) {
649                 ao2_cleanup(rtp->ice_proposed_remote_candidates);
650                 rtp->ice_proposed_remote_candidates = NULL;
651                 return;
652         }
653
654         /* Out with the old, in with the new */
655         ao2_cleanup(rtp->ice_active_remote_candidates);
656         rtp->ice_active_remote_candidates = rtp->ice_proposed_remote_candidates;
657         rtp->ice_proposed_remote_candidates = NULL;
658
659         /* Reset the ICE session. Is this going to work? */
660         if (ice_reset_session(instance)) {
661                 ast_log(LOG_NOTICE, "Failed to create replacement ICE session\n");
662                 return;
663         }
664
665         pj_thread_register_check();
666
667         i = ao2_iterator_init(rtp->ice_active_remote_candidates, 0);
668
669         while ((candidate = ao2_iterator_next(&i)) && (cand_cnt < PJ_ICE_MAX_CAND)) {
670                 pj_str_t address;
671
672                 /* there needs to be at least one rtp and rtcp candidate in the list */
673                 has_rtp |= candidate->id == AST_RTP_ICE_COMPONENT_RTP;
674                 has_rtcp |= candidate->id == AST_RTP_ICE_COMPONENT_RTCP;
675
676                 pj_strdup2(rtp->ice->pool, &candidates[cand_cnt].foundation, candidate->foundation);
677                 candidates[cand_cnt].comp_id = candidate->id;
678                 candidates[cand_cnt].prio = candidate->priority;
679
680                 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->address)), &candidates[cand_cnt].addr);
681
682                 if (!ast_sockaddr_isnull(&candidate->relay_address)) {
683                         pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->relay_address)), &candidates[cand_cnt].rel_addr);
684                 }
685
686                 if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
687                         candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_HOST;
688                 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
689                         candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_SRFLX;
690                 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
691                         candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_RELAYED;
692                 }
693
694                 if (candidate->id == AST_RTP_ICE_COMPONENT_RTP && rtp->turn_rtp) {
695                         pj_turn_sock_set_perm(rtp->turn_rtp, 1, &candidates[cand_cnt].addr, 1);
696                 } else if (candidate->id == AST_RTP_ICE_COMPONENT_RTCP && rtp->turn_rtcp) {
697                         pj_turn_sock_set_perm(rtp->turn_rtcp, 1, &candidates[cand_cnt].addr, 1);
698                 }
699
700                 cand_cnt++;
701                 ao2_ref(candidate, -1);
702         }
703
704         ao2_iterator_destroy(&i);
705
706         if (has_rtp && has_rtcp &&
707             pj_ice_sess_create_check_list(rtp->ice, &ufrag, &passwd, ao2_container_count(
708                                                   rtp->ice_active_remote_candidates), &candidates[0]) == PJ_SUCCESS) {
709                 ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: SUCCESS");
710                 pj_ice_sess_start_check(rtp->ice);
711                 pj_timer_heap_poll(timer_heap, NULL);
712                 rtp->strict_rtp_state = STRICT_RTP_OPEN;
713                 return;
714         }
715
716         ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: FAILURE");
717
718         /* even though create check list failed don't stop ice as
719            it might still work */
720         ast_debug(1, "Failed to create ICE session check list\n");
721         /* however we do need to reset remote candidates since
722            this function may be re-entered */
723         ao2_ref(rtp->ice_active_remote_candidates, -1);
724         rtp->ice_active_remote_candidates = NULL;
725         rtp->ice->rcand_cnt = rtp->ice->clist.count = 0;
726 }
727
728 static const char *ast_rtp_ice_get_ufrag(struct ast_rtp_instance *instance)
729 {
730         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
731
732         return rtp->local_ufrag;
733 }
734
735 static const char *ast_rtp_ice_get_password(struct ast_rtp_instance *instance)
736 {
737         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
738
739         return rtp->local_passwd;
740 }
741
742 static struct ao2_container *ast_rtp_ice_get_local_candidates(struct ast_rtp_instance *instance)
743 {
744         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
745
746         if (rtp->ice_local_candidates) {
747                 ao2_ref(rtp->ice_local_candidates, +1);
748         }
749
750         return rtp->ice_local_candidates;
751 }
752
753 static void ast_rtp_ice_lite(struct ast_rtp_instance *instance)
754 {
755         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
756
757         if (!rtp->ice) {
758                 return;
759         }
760
761         pj_thread_register_check();
762
763         pj_ice_sess_change_role(rtp->ice, PJ_ICE_SESS_ROLE_CONTROLLING);
764 }
765
766 static void ast_rtp_ice_set_role(struct ast_rtp_instance *instance, enum ast_rtp_ice_role role)
767 {
768         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
769
770         if (!rtp->ice) {
771                 return;
772         }
773
774         pj_thread_register_check();
775
776         pj_ice_sess_change_role(rtp->ice, role == AST_RTP_ICE_ROLE_CONTROLLED ?
777                 PJ_ICE_SESS_ROLE_CONTROLLED : PJ_ICE_SESS_ROLE_CONTROLLING);
778 }
779
780 static void ast_rtp_ice_add_cand(struct ast_rtp *rtp, unsigned comp_id, unsigned transport_id, pj_ice_cand_type type, pj_uint16_t local_pref,
781                                         const pj_sockaddr_t *addr, const pj_sockaddr_t *base_addr, const pj_sockaddr_t *rel_addr, int addr_len)
782 {
783         pj_str_t foundation;
784         struct ast_rtp_engine_ice_candidate *candidate, *existing;
785         char address[PJ_INET6_ADDRSTRLEN];
786
787         pj_thread_register_check();
788
789         pj_ice_calc_foundation(rtp->ice->pool, &foundation, type, addr);
790
791         if (!rtp->ice_local_candidates && !(rtp->ice_local_candidates = ao2_container_alloc(1, NULL, ice_candidate_cmp))) {
792                 return;
793         }
794
795         if (!(candidate = ao2_alloc(sizeof(*candidate), ast_rtp_ice_candidate_destroy))) {
796                 return;
797         }
798
799         candidate->foundation = ast_strndup(pj_strbuf(&foundation), pj_strlen(&foundation));
800         candidate->id = comp_id;
801         candidate->transport = ast_strdup("UDP");
802
803         ast_sockaddr_parse(&candidate->address, pj_sockaddr_print(addr, address, sizeof(address), 0), 0);
804         ast_sockaddr_set_port(&candidate->address, pj_sockaddr_get_port(addr));
805
806         if (rel_addr) {
807                 ast_sockaddr_parse(&candidate->relay_address, pj_sockaddr_print(rel_addr, address, sizeof(address), 0), 0);
808                 ast_sockaddr_set_port(&candidate->relay_address, pj_sockaddr_get_port(rel_addr));
809         }
810
811         if (type == PJ_ICE_CAND_TYPE_HOST) {
812                 candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
813         } else if (type == PJ_ICE_CAND_TYPE_SRFLX) {
814                 candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
815         } else if (type == PJ_ICE_CAND_TYPE_RELAYED) {
816                 candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
817         }
818
819         if ((existing = ao2_find(rtp->ice_local_candidates, candidate, OBJ_POINTER))) {
820                 ao2_ref(existing, -1);
821                 ao2_ref(candidate, -1);
822                 return;
823         }
824
825         if (pj_ice_sess_add_cand(rtp->ice, comp_id, transport_id, type, local_pref, &foundation, addr, base_addr, rel_addr, addr_len, NULL) != PJ_SUCCESS) {
826                 ao2_ref(candidate, -1);
827                 return;
828         }
829
830         /* By placing the candidate into the ICE session it will have produced the priority, so update the local candidate with it */
831         candidate->priority = rtp->ice->lcand[rtp->ice->lcand_cnt - 1].prio;
832
833         ao2_link(rtp->ice_local_candidates, candidate);
834         ao2_ref(candidate, -1);
835 }
836
837 static 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)
838 {
839         struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
840         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
841         pj_status_t status;
842
843         status = pj_ice_sess_on_rx_pkt(rtp->ice, AST_RTP_ICE_COMPONENT_RTP, TRANSPORT_TURN_RTP, pkt, pkt_len, peer_addr,
844                 addr_len);
845         if (status != PJ_SUCCESS) {
846                 char buf[100];
847
848                 pj_strerror(status, buf, sizeof(buf));
849                 ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
850                         (int)status, buf);
851                 return;
852         }
853         if (!rtp->rtp_passthrough) {
854                 return;
855         }
856         rtp->rtp_passthrough = 0;
857
858         ast_sendto(rtp->s, pkt, pkt_len, 0, &rtp->rtp_loop);
859 }
860
861 static void ast_rtp_on_turn_rtp_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, pj_turn_state_t new_state)
862 {
863         struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
864         struct ast_rtp *rtp;
865
866         /* If this is a leftover from an already notified RTP instance just ignore the state change */
867         if (!instance) {
868                 return;
869         }
870
871         rtp = ast_rtp_instance_get_data(instance);
872
873         /* We store the new state so the other thread can actually handle it */
874         ast_mutex_lock(&rtp->lock);
875         rtp->turn_state = new_state;
876         ast_cond_signal(&rtp->cond);
877
878         if (new_state == PJ_TURN_STATE_DESTROYING) {
879                 pj_turn_sock_set_user_data(rtp->turn_rtp, NULL);
880                 rtp->turn_rtp = NULL;
881         }
882
883         ast_mutex_unlock(&rtp->lock);
884 }
885
886 /* RTP TURN Socket interface declaration */
887 static pj_turn_sock_cb ast_rtp_turn_rtp_sock_cb = {
888         .on_rx_data = ast_rtp_on_turn_rx_rtp_data,
889         .on_state = ast_rtp_on_turn_rtp_state,
890 };
891
892 static 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)
893 {
894         struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
895         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
896         pj_status_t status;
897
898         status = pj_ice_sess_on_rx_pkt(rtp->ice, AST_RTP_ICE_COMPONENT_RTCP, TRANSPORT_TURN_RTCP, pkt, pkt_len, peer_addr,
899                 addr_len);
900         if (status != PJ_SUCCESS) {
901                 char buf[100];
902
903                 pj_strerror(status, buf, sizeof(buf));
904                 ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
905                         (int)status, buf);
906                 return;
907         }
908         if (!rtp->rtcp_passthrough) {
909                 return;
910         }
911         rtp->rtcp_passthrough = 0;
912
913         ast_sendto(rtp->rtcp->s, pkt, pkt_len, 0, &rtp->rtcp_loop);
914 }
915
916 static void ast_rtp_on_turn_rtcp_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, pj_turn_state_t new_state)
917 {
918         struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
919         struct ast_rtp *rtp = NULL;
920
921         /* If this is a leftover from an already destroyed RTP instance just ignore the state change */
922         if (!instance) {
923                 return;
924         }
925
926         rtp = ast_rtp_instance_get_data(instance);
927
928         /* We store the new state so the other thread can actually handle it */
929         ast_mutex_lock(&rtp->lock);
930         rtp->turn_state = new_state;
931         ast_cond_signal(&rtp->cond);
932
933         if (new_state == PJ_TURN_STATE_DESTROYING) {
934                 pj_turn_sock_set_user_data(rtp->turn_rtcp, NULL);
935                 rtp->turn_rtcp = NULL;
936         }
937
938         ast_mutex_unlock(&rtp->lock);
939 }
940
941 /* RTCP TURN Socket interface declaration */
942 static pj_turn_sock_cb ast_rtp_turn_rtcp_sock_cb = {
943         .on_rx_data = ast_rtp_on_turn_rx_rtcp_data,
944         .on_state = ast_rtp_on_turn_rtcp_state,
945 };
946
947 /*! \brief Worker thread for ioqueue and timerheap */
948 static int ioqueue_worker_thread(void *data)
949 {
950         struct ast_rtp_ioqueue_thread *ioqueue = data;
951
952         while (!ioqueue->terminate) {
953                 const pj_time_val delay = {0, 10};
954
955                 pj_ioqueue_poll(ioqueue->ioqueue, &delay);
956
957                 pj_timer_heap_poll(ioqueue->timerheap, NULL);
958         }
959
960         return 0;
961 }
962
963 /*! \brief Destroyer for ioqueue thread */
964 static void rtp_ioqueue_thread_destroy(struct ast_rtp_ioqueue_thread *ioqueue)
965 {
966         if (ioqueue->thread) {
967                 ioqueue->terminate = 1;
968                 pj_thread_join(ioqueue->thread);
969                 pj_thread_destroy(ioqueue->thread);
970         }
971
972         pj_pool_release(ioqueue->pool);
973         ast_free(ioqueue);
974 }
975
976 /*! \brief Removal function for ioqueue thread, determines if it should be terminated and destroyed */
977 static void rtp_ioqueue_thread_remove(struct ast_rtp_ioqueue_thread *ioqueue)
978 {
979         int destroy = 0;
980
981         /* If nothing is using this ioqueue thread destroy it */
982         AST_LIST_LOCK(&ioqueues);
983         if ((ioqueue->count - 2) == 0) {
984                 destroy = 1;
985                 AST_LIST_REMOVE(&ioqueues, ioqueue, next);
986         }
987         AST_LIST_UNLOCK(&ioqueues);
988
989         if (!destroy) {
990                 return;
991         }
992
993         rtp_ioqueue_thread_destroy(ioqueue);
994 }
995
996 /*! \brief Finder and allocator for an ioqueue thread */
997 static struct ast_rtp_ioqueue_thread *rtp_ioqueue_thread_get_or_create(void)
998 {
999         struct ast_rtp_ioqueue_thread *ioqueue;
1000         pj_lock_t *lock;
1001
1002         AST_LIST_LOCK(&ioqueues);
1003
1004         /* See if an ioqueue thread exists that can handle more */
1005         AST_LIST_TRAVERSE(&ioqueues, ioqueue, next) {
1006                 if ((ioqueue->count + 2) < PJ_IOQUEUE_MAX_HANDLES) {
1007                         break;
1008                 }
1009         }
1010
1011         /* If we found one bump it up and return it */
1012         if (ioqueue) {
1013                 ioqueue->count += 2;
1014                 goto end;
1015         }
1016
1017         ioqueue = ast_calloc(1, sizeof(*ioqueue));
1018         if (!ioqueue) {
1019                 goto end;
1020         }
1021
1022         ioqueue->pool = pj_pool_create(&cachingpool.factory, "rtp", 512, 512, NULL);
1023
1024         /* We use a timer on the ioqueue thread for TURN so that two threads aren't operating
1025          * on a session at the same time
1026          */
1027         if (pj_timer_heap_create(ioqueue->pool, 4, &ioqueue->timerheap) != PJ_SUCCESS) {
1028                 goto fatal;
1029         }
1030
1031         if (pj_lock_create_recursive_mutex(ioqueue->pool, "rtp%p", &lock) != PJ_SUCCESS) {
1032                 goto fatal;
1033         }
1034
1035         pj_timer_heap_set_lock(ioqueue->timerheap, lock, PJ_TRUE);
1036
1037         if (pj_ioqueue_create(ioqueue->pool, PJ_IOQUEUE_MAX_HANDLES, &ioqueue->ioqueue) != PJ_SUCCESS) {
1038                 goto fatal;
1039         }
1040
1041         if (pj_thread_create(ioqueue->pool, "ice", &ioqueue_worker_thread, ioqueue, 0, 0, &ioqueue->thread) != PJ_SUCCESS) {
1042                 goto fatal;
1043         }
1044
1045         AST_LIST_INSERT_HEAD(&ioqueues, ioqueue, next);
1046
1047         /* Since this is being returned to an active session the count always starts at 2 */
1048         ioqueue->count = 2;
1049
1050         goto end;
1051
1052 fatal:
1053         rtp_ioqueue_thread_destroy(ioqueue);
1054         ioqueue = NULL;
1055
1056 end:
1057         AST_LIST_UNLOCK(&ioqueues);
1058         return ioqueue;
1059 }
1060
1061 static void ast_rtp_ice_turn_request(struct ast_rtp_instance *instance, enum ast_rtp_ice_component_type component,
1062                 enum ast_transport transport, const char *server, unsigned int port, const char *username, const char *password)
1063 {
1064         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1065         pj_turn_sock **turn_sock;
1066         const pj_turn_sock_cb *turn_cb;
1067         pj_turn_tp_type conn_type;
1068         int conn_transport;
1069         pj_stun_auth_cred cred = { 0, };
1070         pj_str_t turn_addr;
1071         struct ast_sockaddr addr = { { 0, } };
1072         pj_stun_config stun_config;
1073         struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
1074         struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
1075         pj_turn_session_info info;
1076         struct ast_sockaddr local, loop;
1077
1078         ast_rtp_instance_get_local_address(instance, &local);
1079         if (ast_sockaddr_is_ipv4(&local)) {
1080                 ast_sockaddr_parse(&loop, "127.0.0.1", PARSE_PORT_FORBID);
1081         } else {
1082                 ast_sockaddr_parse(&loop, "::1", PARSE_PORT_FORBID);
1083         }
1084
1085         /* Determine what component we are requesting a TURN session for */
1086         if (component == AST_RTP_ICE_COMPONENT_RTP) {
1087                 turn_sock = &rtp->turn_rtp;
1088                 turn_cb = &ast_rtp_turn_rtp_sock_cb;
1089                 conn_transport = TRANSPORT_TURN_RTP;
1090                 ast_sockaddr_set_port(&loop, ast_sockaddr_port(&local));
1091         } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
1092                 turn_sock = &rtp->turn_rtcp;
1093                 turn_cb = &ast_rtp_turn_rtcp_sock_cb;
1094                 conn_transport = TRANSPORT_TURN_RTCP;
1095                 ast_sockaddr_set_port(&loop, ast_sockaddr_port(&rtp->rtcp->us));
1096         } else {
1097                 return;
1098         }
1099
1100         if (transport == AST_TRANSPORT_UDP) {
1101                 conn_type = PJ_TURN_TP_UDP;
1102         } else if (transport == AST_TRANSPORT_TCP) {
1103                 conn_type = PJ_TURN_TP_TCP;
1104         } else {
1105                 ast_assert(0);
1106                 return;
1107         }
1108
1109         ast_sockaddr_parse(&addr, server, PARSE_PORT_FORBID);
1110
1111         ast_mutex_lock(&rtp->lock);
1112         if (*turn_sock) {
1113                 pj_turn_sock_destroy(*turn_sock);
1114                 rtp->turn_state = PJ_TURN_STATE_NULL;
1115                 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
1116                         ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
1117                 }
1118         }
1119         ast_mutex_unlock(&rtp->lock);
1120
1121         if (component == AST_RTP_ICE_COMPONENT_RTP && !rtp->ioqueue) {
1122                 rtp->ioqueue = rtp_ioqueue_thread_get_or_create();
1123                 if (!rtp->ioqueue) {
1124                         return;
1125                 }
1126         }
1127
1128         pj_stun_config_init(&stun_config, &cachingpool.factory, 0, rtp->ioqueue->ioqueue, rtp->ioqueue->timerheap);
1129
1130         if (pj_turn_sock_create(&stun_config, ast_sockaddr_is_ipv4(&addr) ? pj_AF_INET() : pj_AF_INET6(), conn_type,
1131                 turn_cb, NULL, instance, turn_sock) != PJ_SUCCESS) {
1132                 ast_log(LOG_WARNING, "Could not create a TURN client socket\n");
1133                 return;
1134         }
1135
1136         cred.type = PJ_STUN_AUTH_CRED_STATIC;
1137         pj_strset2(&cred.data.static_cred.username, (char*)username);
1138         cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
1139         pj_strset2(&cred.data.static_cred.data, (char*)password);
1140
1141         /* Because the TURN socket is asynchronous but we are synchronous we need to wait until it is done */
1142         ast_mutex_lock(&rtp->lock);
1143         pj_turn_sock_alloc(*turn_sock, pj_cstr(&turn_addr, server), port, NULL, &cred, NULL);
1144         while (rtp->turn_state < PJ_TURN_STATE_READY) {
1145                 ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
1146         }
1147         ast_mutex_unlock(&rtp->lock);
1148
1149         /* If a TURN session was allocated add it as a candidate */
1150         if (rtp->turn_state != PJ_TURN_STATE_READY) {
1151                 return;
1152         }
1153
1154         pj_turn_sock_get_info(*turn_sock, &info);
1155
1156         ast_rtp_ice_add_cand(rtp, component, conn_transport, PJ_ICE_CAND_TYPE_RELAYED, 65535, &info.relay_addr,
1157                 &info.relay_addr, &info.mapped_addr, pj_sockaddr_get_len(&info.relay_addr));
1158
1159         if (component == AST_RTP_ICE_COMPONENT_RTP) {
1160                 ast_sockaddr_copy(&rtp->rtp_loop, &loop);
1161         } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
1162                 ast_sockaddr_copy(&rtp->rtcp_loop, &loop);
1163         }
1164 }
1165
1166 static char *generate_random_string(char *buf, size_t size)
1167 {
1168         long val[4];
1169         int x;
1170
1171         for (x=0; x<4; x++) {
1172                 val[x] = ast_random();
1173         }
1174         snprintf(buf, size, "%08lx%08lx%08lx%08lx", (long unsigned)val[0], (long unsigned)val[1], (long unsigned)val[2], (long unsigned)val[3]);
1175
1176         return buf;
1177 }
1178
1179 /* ICE RTP Engine interface declaration */
1180 static struct ast_rtp_engine_ice ast_rtp_ice = {
1181         .set_authentication = ast_rtp_ice_set_authentication,
1182         .add_remote_candidate = ast_rtp_ice_add_remote_candidate,
1183         .start = ast_rtp_ice_start,
1184         .stop = ast_rtp_ice_stop,
1185         .get_ufrag = ast_rtp_ice_get_ufrag,
1186         .get_password = ast_rtp_ice_get_password,
1187         .get_local_candidates = ast_rtp_ice_get_local_candidates,
1188         .ice_lite = ast_rtp_ice_lite,
1189         .set_role = ast_rtp_ice_set_role,
1190         .turn_request = ast_rtp_ice_turn_request,
1191 };
1192 #endif
1193
1194 #ifdef HAVE_OPENSSL_SRTP
1195 static int dtls_verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
1196 {
1197         /* We don't want to actually verify the certificate so just accept what they have provided */
1198         return 1;
1199 }
1200
1201 static int dtls_details_initialize(struct dtls_details *dtls, SSL_CTX *ssl_ctx,
1202         enum ast_rtp_dtls_setup setup)
1203 {
1204         dtls->dtls_setup = setup;
1205
1206         if (!(dtls->ssl = SSL_new(ssl_ctx))) {
1207                 ast_log(LOG_ERROR, "Failed to allocate memory for SSL\n");
1208                 goto error;
1209         }
1210
1211         if (!(dtls->read_bio = BIO_new(BIO_s_mem()))) {
1212                 ast_log(LOG_ERROR, "Failed to allocate memory for inbound SSL traffic\n");
1213                 goto error;
1214         }
1215         BIO_set_mem_eof_return(dtls->read_bio, -1);
1216
1217         if (!(dtls->write_bio = BIO_new(BIO_s_mem()))) {
1218                 ast_log(LOG_ERROR, "Failed to allocate memory for outbound SSL traffic\n");
1219                 goto error;
1220         }
1221         BIO_set_mem_eof_return(dtls->write_bio, -1);
1222
1223         SSL_set_bio(dtls->ssl, dtls->read_bio, dtls->write_bio);
1224
1225         if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
1226                 SSL_set_accept_state(dtls->ssl);
1227         } else {
1228                 SSL_set_connect_state(dtls->ssl);
1229         }
1230         dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
1231
1232         return 0;
1233
1234 error:
1235         if (dtls->read_bio) {
1236                 BIO_free(dtls->read_bio);
1237                 dtls->read_bio = NULL;
1238         }
1239
1240         if (dtls->write_bio) {
1241                 BIO_free(dtls->write_bio);
1242                 dtls->write_bio = NULL;
1243         }
1244
1245         if (dtls->ssl) {
1246                 SSL_free(dtls->ssl);
1247                 dtls->ssl = NULL;
1248         }
1249         return -1;
1250 }
1251
1252 static int dtls_setup_rtcp(struct ast_rtp_instance *instance)
1253 {
1254         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1255
1256         if (!rtp->ssl_ctx || !rtp->rtcp) {
1257                 return 0;
1258         }
1259
1260         return dtls_details_initialize(&rtp->rtcp->dtls, rtp->ssl_ctx, rtp->dtls.dtls_setup);
1261 }
1262
1263 static int ast_rtp_dtls_set_configuration(struct ast_rtp_instance *instance, const struct ast_rtp_dtls_cfg *dtls_cfg)
1264 {
1265         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1266         int res;
1267
1268         if (!dtls_cfg->enabled) {
1269                 return 0;
1270         }
1271
1272         if (!ast_rtp_engine_srtp_is_registered()) {
1273                 ast_log(LOG_ERROR, "SRTP support module is not loaded or available. Try loading res_srtp.so.\n");
1274                 return -1;
1275         }
1276
1277         if (rtp->ssl_ctx) {
1278                 return 0;
1279         }
1280
1281         if (!(rtp->ssl_ctx = SSL_CTX_new(DTLSv1_method()))) {
1282                 return -1;
1283         }
1284
1285         SSL_CTX_set_read_ahead(rtp->ssl_ctx, 1);
1286
1287         rtp->dtls_verify = dtls_cfg->verify;
1288
1289         SSL_CTX_set_verify(rtp->ssl_ctx, (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) || (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
1290                 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE, !(rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
1291                 dtls_verify_callback : NULL);
1292
1293         if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_80) {
1294                 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_80");
1295         } else if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_32) {
1296                 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_32");
1297         } else {
1298                 ast_log(LOG_ERROR, "Unsupported suite specified for DTLS-SRTP on RTP instance '%p'\n", instance);
1299                 return -1;
1300         }
1301
1302         rtp->local_hash = dtls_cfg->hash;
1303
1304         if (!ast_strlen_zero(dtls_cfg->certfile)) {
1305                 char *private = ast_strlen_zero(dtls_cfg->pvtfile) ? dtls_cfg->certfile : dtls_cfg->pvtfile;
1306                 BIO *certbio;
1307                 X509 *cert;
1308                 const EVP_MD *type;
1309                 unsigned int size, i;
1310                 unsigned char fingerprint[EVP_MAX_MD_SIZE];
1311                 char *local_fingerprint = rtp->local_fingerprint;
1312
1313                 if (!SSL_CTX_use_certificate_file(rtp->ssl_ctx, dtls_cfg->certfile, SSL_FILETYPE_PEM)) {
1314                         ast_log(LOG_ERROR, "Specified certificate file '%s' for RTP instance '%p' could not be used\n",
1315                                 dtls_cfg->certfile, instance);
1316                         return -1;
1317                 }
1318
1319                 if (!SSL_CTX_use_PrivateKey_file(rtp->ssl_ctx, private, SSL_FILETYPE_PEM) ||
1320                     !SSL_CTX_check_private_key(rtp->ssl_ctx)) {
1321                         ast_log(LOG_ERROR, "Specified private key file '%s' for RTP instance '%p' could not be used\n",
1322                                 private, instance);
1323                         return -1;
1324                 }
1325
1326                 if (!(certbio = BIO_new(BIO_s_file()))) {
1327                         ast_log(LOG_ERROR, "Failed to allocate memory for certificate fingerprinting on RTP instance '%p'\n",
1328                                 instance);
1329                         return -1;
1330                 }
1331
1332                 if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA1) {
1333                         type = EVP_sha1();
1334                 } else if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA256) {
1335                         type = EVP_sha256();
1336                 } else {
1337                         ast_log(LOG_ERROR, "Unsupported fingerprint hash type on RTP instance '%p'\n",
1338                                 instance);
1339                         return -1;
1340                 }
1341
1342                 if (!BIO_read_filename(certbio, dtls_cfg->certfile) ||
1343                     !(cert = PEM_read_bio_X509(certbio, NULL, 0, NULL)) ||
1344                     !X509_digest(cert, type, fingerprint, &size) ||
1345                     !size) {
1346                         ast_log(LOG_ERROR, "Could not produce fingerprint from certificate '%s' for RTP instance '%p'\n",
1347                                 dtls_cfg->certfile, instance);
1348                         BIO_free_all(certbio);
1349                         return -1;
1350                 }
1351
1352                 for (i = 0; i < size; i++) {
1353                         sprintf(local_fingerprint, "%02hhX:", fingerprint[i]);
1354                         local_fingerprint += 3;
1355                 }
1356
1357                 *(local_fingerprint-1) = 0;
1358
1359                 BIO_free_all(certbio);
1360         }
1361
1362         if (!ast_strlen_zero(dtls_cfg->cipher)) {
1363                 if (!SSL_CTX_set_cipher_list(rtp->ssl_ctx, dtls_cfg->cipher)) {
1364                         ast_log(LOG_ERROR, "Invalid cipher specified in cipher list '%s' for RTP instance '%p'\n",
1365                                 dtls_cfg->cipher, instance);
1366                         return -1;
1367                 }
1368         }
1369
1370         if (!ast_strlen_zero(dtls_cfg->cafile) || !ast_strlen_zero(dtls_cfg->capath)) {
1371                 if (!SSL_CTX_load_verify_locations(rtp->ssl_ctx, S_OR(dtls_cfg->cafile, NULL), S_OR(dtls_cfg->capath, NULL))) {
1372                         ast_log(LOG_ERROR, "Invalid certificate authority file '%s' or path '%s' specified for RTP instance '%p'\n",
1373                                 S_OR(dtls_cfg->cafile, ""), S_OR(dtls_cfg->capath, ""), instance);
1374                         return -1;
1375                 }
1376         }
1377
1378         rtp->rekey = dtls_cfg->rekey;
1379         rtp->suite = dtls_cfg->suite;
1380
1381         res = dtls_details_initialize(&rtp->dtls, rtp->ssl_ctx, dtls_cfg->default_setup);
1382         if (!res) {
1383                 dtls_setup_rtcp(instance);
1384         }
1385
1386         return res;
1387 }
1388
1389 static int ast_rtp_dtls_active(struct ast_rtp_instance *instance)
1390 {
1391         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1392
1393         return !rtp->ssl_ctx ? 0 : 1;
1394 }
1395
1396 static void ast_rtp_dtls_stop(struct ast_rtp_instance *instance)
1397 {
1398         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1399
1400         if (rtp->ssl_ctx) {
1401                 SSL_CTX_free(rtp->ssl_ctx);
1402                 rtp->ssl_ctx = NULL;
1403         }
1404
1405         if (rtp->dtls.ssl) {
1406                 SSL_free(rtp->dtls.ssl);
1407                 rtp->dtls.ssl = NULL;
1408         }
1409
1410         if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
1411                 SSL_free(rtp->rtcp->dtls.ssl);
1412                 rtp->rtcp->dtls.ssl = NULL;
1413         }
1414 }
1415
1416 static void ast_rtp_dtls_reset(struct ast_rtp_instance *instance)
1417 {
1418         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1419
1420         if (SSL_is_init_finished(rtp->dtls.ssl)) {
1421                 SSL_shutdown(rtp->dtls.ssl);
1422                 rtp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
1423         }
1424
1425         if (rtp->rtcp && SSL_is_init_finished(rtp->rtcp->dtls.ssl)) {
1426                 SSL_shutdown(rtp->rtcp->dtls.ssl);
1427                 rtp->rtcp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
1428         }
1429 }
1430
1431 static enum ast_rtp_dtls_connection ast_rtp_dtls_get_connection(struct ast_rtp_instance *instance)
1432 {
1433         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1434
1435         return rtp->dtls.connection;
1436 }
1437
1438 static enum ast_rtp_dtls_setup ast_rtp_dtls_get_setup(struct ast_rtp_instance *instance)
1439 {
1440         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1441
1442         return rtp->dtls.dtls_setup;
1443 }
1444
1445 static void dtls_set_setup(enum ast_rtp_dtls_setup *dtls_setup, enum ast_rtp_dtls_setup setup, SSL *ssl)
1446 {
1447         enum ast_rtp_dtls_setup old = *dtls_setup;
1448
1449         switch (setup) {
1450         case AST_RTP_DTLS_SETUP_ACTIVE:
1451                 *dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
1452                 break;
1453         case AST_RTP_DTLS_SETUP_PASSIVE:
1454                 *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
1455                 break;
1456         case AST_RTP_DTLS_SETUP_ACTPASS:
1457                 /* We can't respond to an actpass setup with actpass ourselves... so respond with active, as we can initiate connections */
1458                 if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
1459                         *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
1460                 }
1461                 break;
1462         case AST_RTP_DTLS_SETUP_HOLDCONN:
1463                 *dtls_setup = AST_RTP_DTLS_SETUP_HOLDCONN;
1464                 break;
1465         default:
1466                 /* This should never occur... if it does exit early as we don't know what state things are in */
1467                 return;
1468         }
1469
1470         /* If the setup state did not change we go on as if nothing happened */
1471         if (old == *dtls_setup) {
1472                 return;
1473         }
1474
1475         /* If they don't want us to establish a connection wait until later */
1476         if (*dtls_setup == AST_RTP_DTLS_SETUP_HOLDCONN) {
1477                 return;
1478         }
1479
1480         if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
1481                 SSL_set_connect_state(ssl);
1482         } else if (*dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
1483                 SSL_set_accept_state(ssl);
1484         } else {
1485                 return;
1486         }
1487 }
1488
1489 static void ast_rtp_dtls_set_setup(struct ast_rtp_instance *instance, enum ast_rtp_dtls_setup setup)
1490 {
1491         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1492
1493         if (rtp->dtls.ssl) {
1494                 dtls_set_setup(&rtp->dtls.dtls_setup, setup, rtp->dtls.ssl);
1495         }
1496
1497         if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
1498                 dtls_set_setup(&rtp->rtcp->dtls.dtls_setup, setup, rtp->rtcp->dtls.ssl);
1499         }
1500 }
1501
1502 static void ast_rtp_dtls_set_fingerprint(struct ast_rtp_instance *instance, enum ast_rtp_dtls_hash hash, const char *fingerprint)
1503 {
1504         char *tmp = ast_strdupa(fingerprint), *value;
1505         int pos = 0;
1506         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1507
1508         if (hash != AST_RTP_DTLS_HASH_SHA1 && hash != AST_RTP_DTLS_HASH_SHA256) {
1509                 return;
1510         }
1511
1512         rtp->remote_hash = hash;
1513
1514         while ((value = strsep(&tmp, ":")) && (pos != (EVP_MAX_MD_SIZE - 1))) {
1515                 sscanf(value, "%02hhx", &rtp->remote_fingerprint[pos++]);
1516         }
1517 }
1518
1519 static enum ast_rtp_dtls_hash ast_rtp_dtls_get_fingerprint_hash(struct ast_rtp_instance *instance)
1520 {
1521         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1522
1523         return rtp->local_hash;
1524 }
1525
1526 static const char *ast_rtp_dtls_get_fingerprint(struct ast_rtp_instance *instance)
1527 {
1528         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1529
1530         return rtp->local_fingerprint;
1531 }
1532
1533 /* DTLS RTP Engine interface declaration */
1534 static struct ast_rtp_engine_dtls ast_rtp_dtls = {
1535         .set_configuration = ast_rtp_dtls_set_configuration,
1536         .active = ast_rtp_dtls_active,
1537         .stop = ast_rtp_dtls_stop,
1538         .reset = ast_rtp_dtls_reset,
1539         .get_connection = ast_rtp_dtls_get_connection,
1540         .get_setup = ast_rtp_dtls_get_setup,
1541         .set_setup = ast_rtp_dtls_set_setup,
1542         .set_fingerprint = ast_rtp_dtls_set_fingerprint,
1543         .get_fingerprint_hash = ast_rtp_dtls_get_fingerprint_hash,
1544         .get_fingerprint = ast_rtp_dtls_get_fingerprint,
1545 };
1546
1547 #endif
1548
1549 /* RTP Engine Declaration */
1550 static struct ast_rtp_engine asterisk_rtp_engine = {
1551         .name = "asterisk",
1552         .new = ast_rtp_new,
1553         .destroy = ast_rtp_destroy,
1554         .dtmf_begin = ast_rtp_dtmf_begin,
1555         .dtmf_end = ast_rtp_dtmf_end,
1556         .dtmf_end_with_duration = ast_rtp_dtmf_end_with_duration,
1557         .dtmf_mode_set = ast_rtp_dtmf_mode_set,
1558         .dtmf_mode_get = ast_rtp_dtmf_mode_get,
1559         .update_source = ast_rtp_update_source,
1560         .change_source = ast_rtp_change_source,
1561         .write = ast_rtp_write,
1562         .read = ast_rtp_read,
1563         .prop_set = ast_rtp_prop_set,
1564         .fd = ast_rtp_fd,
1565         .remote_address_set = ast_rtp_remote_address_set,
1566         .red_init = rtp_red_init,
1567         .red_buffer = rtp_red_buffer,
1568         .local_bridge = ast_rtp_local_bridge,
1569         .get_stat = ast_rtp_get_stat,
1570         .dtmf_compatible = ast_rtp_dtmf_compatible,
1571         .stun_request = ast_rtp_stun_request,
1572         .stop = ast_rtp_stop,
1573         .qos = ast_rtp_qos_set,
1574         .sendcng = ast_rtp_sendcng,
1575 #ifdef HAVE_PJPROJECT
1576         .ice = &ast_rtp_ice,
1577 #endif
1578 #ifdef HAVE_OPENSSL_SRTP
1579         .dtls = &ast_rtp_dtls,
1580         .activate = ast_rtp_activate,
1581 #endif
1582 };
1583
1584 #ifdef HAVE_OPENSSL_SRTP
1585 static void dtls_perform_handshake(struct ast_rtp_instance *instance, struct dtls_details *dtls, int rtcp)
1586 {
1587         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1588
1589         if (!dtls->ssl) {
1590                 return;
1591         }
1592
1593         if (SSL_is_init_finished(dtls->ssl)) {
1594                 SSL_clear(dtls->ssl);
1595                 if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
1596                         SSL_set_accept_state(dtls->ssl);
1597                 } else {
1598                         SSL_set_connect_state(dtls->ssl);
1599                 }
1600                 dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
1601         }
1602         SSL_do_handshake(dtls->ssl);
1603         dtls_srtp_check_pending(instance, rtp, rtcp);
1604 }
1605 #endif
1606
1607 #ifdef HAVE_PJPROJECT
1608 static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq);
1609
1610 static void ast_rtp_on_ice_complete(pj_ice_sess *ice, pj_status_t status)
1611 {
1612         struct ast_rtp_instance *instance = ice->user_data;
1613         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1614
1615         if (status == PJ_SUCCESS) {
1616                 struct ast_sockaddr remote_address;
1617
1618                 /* Symmetric RTP must be disabled for the remote address to not get overwritten */
1619                 ast_rtp_instance_set_prop(instance, AST_RTP_PROPERTY_NAT, 0);
1620
1621                 update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
1622                 ast_rtp_instance_set_remote_address(instance, &remote_address);
1623
1624                 if (rtp->rtcp) {
1625                         update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTCP, &rtp->rtcp->them);
1626                 }
1627         }
1628  
1629 #ifdef HAVE_OPENSSL_SRTP
1630         dtls_perform_handshake(instance, &rtp->dtls, 0);
1631
1632         if (rtp->rtcp) {
1633                 dtls_perform_handshake(instance, &rtp->rtcp->dtls, 1);
1634         }
1635 #endif
1636
1637         if (!strictrtp) {
1638                 return;
1639         }
1640
1641         rtp->strict_rtp_state = STRICT_RTP_LEARN;
1642         rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t)rtp->seqno);
1643 }
1644
1645 static 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)
1646 {
1647         struct ast_rtp_instance *instance = ice->user_data;
1648         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1649
1650         /* Instead of handling the packet here (which really doesn't work with our architecture) we set a bit to indicate that it should be handled after pj_ice_sess_on_rx_pkt
1651          * returns */
1652         if (transport_id == TRANSPORT_SOCKET_RTP || transport_id == TRANSPORT_SOCKET_RTCP) {
1653                 rtp->passthrough = 1;
1654         } else if (transport_id == TRANSPORT_TURN_RTP) {
1655                 rtp->rtp_passthrough = 1;
1656         } else if (transport_id == TRANSPORT_TURN_RTCP) {
1657                 rtp->rtcp_passthrough = 1;
1658         }
1659 }
1660
1661 static 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)
1662 {
1663         struct ast_rtp_instance *instance = ice->user_data;
1664         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1665         pj_status_t status = PJ_EINVALIDOP;
1666         pj_ssize_t _size = (pj_ssize_t)size;
1667
1668         if (transport_id == TRANSPORT_SOCKET_RTP) {
1669                 /* Traffic is destined to go right out the RTP socket we already have */
1670                 status = pj_sock_sendto(rtp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
1671                 /* sendto on a connectionless socket should send all the data, or none at all */
1672                 ast_assert(_size == size || status != PJ_SUCCESS);
1673         } else if (transport_id == TRANSPORT_SOCKET_RTCP) {
1674                 /* Traffic is destined to go right out the RTCP socket we already have */
1675                 if (rtp->rtcp) {
1676                         status = pj_sock_sendto(rtp->rtcp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
1677                         /* sendto on a connectionless socket should send all the data, or none at all */
1678                         ast_assert(_size == size || status != PJ_SUCCESS);
1679                 } else {
1680                         status = PJ_SUCCESS;
1681                 }
1682         } else if (transport_id == TRANSPORT_TURN_RTP) {
1683                 /* Traffic is going through the RTP TURN relay */
1684                 if (rtp->turn_rtp) {
1685                         status = pj_turn_sock_sendto(rtp->turn_rtp, pkt, size, dst_addr, dst_addr_len);
1686                 }
1687         } else if (transport_id == TRANSPORT_TURN_RTCP) {
1688                 /* Traffic is going through the RTCP TURN relay */
1689                 if (rtp->turn_rtcp) {
1690                         status = pj_turn_sock_sendto(rtp->turn_rtcp, pkt, size, dst_addr, dst_addr_len);
1691                 }
1692         }
1693
1694         return status;
1695 }
1696
1697 /* ICE Session interface declaration */
1698 static pj_ice_sess_cb ast_rtp_ice_sess_cb = {
1699         .on_ice_complete = ast_rtp_on_ice_complete,
1700         .on_rx_data = ast_rtp_on_ice_rx_data,
1701         .on_tx_pkt = ast_rtp_on_ice_tx_pkt,
1702 };
1703
1704 /*! \brief Worker thread for timerheap */
1705 static int timer_worker_thread(void *data)
1706 {
1707         pj_ioqueue_t *ioqueue;
1708
1709         if (pj_ioqueue_create(pool, 1, &ioqueue) != PJ_SUCCESS) {
1710                 return -1;
1711         }
1712
1713         while (!timer_terminate) {
1714                 const pj_time_val delay = {0, 10};
1715
1716                 pj_timer_heap_poll(timer_heap, NULL);
1717                 pj_ioqueue_poll(ioqueue, &delay);
1718         }
1719
1720         return 0;
1721 }
1722 #endif
1723
1724 static inline int rtp_debug_test_addr(struct ast_sockaddr *addr)
1725 {
1726         if (!rtpdebug) {
1727                 return 0;
1728         }
1729         if (!ast_sockaddr_isnull(&rtpdebugaddr)) {
1730                 if (rtpdebugport) {
1731                         return (ast_sockaddr_cmp(&rtpdebugaddr, addr) == 0); /* look for RTP packets from IP+Port */
1732                 } else {
1733                         return (ast_sockaddr_cmp_addr(&rtpdebugaddr, addr) == 0); /* only look for RTP packets from IP */
1734                 }
1735         }
1736
1737         return 1;
1738 }
1739
1740 static inline int rtcp_debug_test_addr(struct ast_sockaddr *addr)
1741 {
1742         if (!rtcpdebug) {
1743                 return 0;
1744         }
1745         if (!ast_sockaddr_isnull(&rtcpdebugaddr)) {
1746                 if (rtcpdebugport) {
1747                         return (ast_sockaddr_cmp(&rtcpdebugaddr, addr) == 0); /* look for RTCP packets from IP+Port */
1748                 } else {
1749                         return (ast_sockaddr_cmp_addr(&rtcpdebugaddr, addr) == 0); /* only look for RTCP packets from IP */
1750                 }
1751         }
1752
1753         return 1;
1754 }
1755
1756 #ifdef HAVE_OPENSSL_SRTP
1757
1758 static int dtls_srtp_handle_timeout(const void *data)
1759 {
1760         struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
1761         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1762
1763         if (!rtp)
1764         {
1765                 return 0;
1766         }
1767
1768         ast_mutex_lock(&rtp->dtls_timer_lock);
1769         if (rtp->dtlstimerid == -1)
1770         {
1771                 ast_mutex_unlock(&rtp->dtls_timer_lock);
1772                 ao2_ref(instance, -1);
1773                 return 0;
1774         }
1775
1776         rtp->dtlstimerid = -1;
1777         ast_mutex_unlock(&rtp->dtls_timer_lock);
1778
1779         if (rtp->dtls.ssl && !SSL_is_init_finished(rtp->dtls.ssl)) {
1780                 DTLSv1_handle_timeout(rtp->dtls.ssl);
1781         }
1782         dtls_srtp_check_pending(instance, rtp, 0);
1783
1784         if (rtp->rtcp && rtp->rtcp->dtls.ssl && !SSL_is_init_finished(rtp->rtcp->dtls.ssl)) {
1785                 DTLSv1_handle_timeout(rtp->rtcp->dtls.ssl);
1786         }
1787         dtls_srtp_check_pending(instance, rtp, 1);
1788
1789         ao2_ref(instance, -1);
1790
1791         return 0;
1792 }
1793
1794 static void dtls_srtp_check_pending(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
1795 {
1796         struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
1797         size_t pending;
1798         struct timeval dtls_timeout; /* timeout on DTLS  */
1799
1800         if (!dtls->ssl || !dtls->write_bio) {
1801                 return;
1802         }
1803
1804         pending = BIO_ctrl_pending(dtls->write_bio);
1805
1806         if (pending > 0) {
1807                 char outgoing[pending];
1808                 size_t out;
1809                 struct ast_sockaddr remote_address = { {0, } };
1810                 int ice;
1811
1812                 if (!rtcp) {
1813                         ast_rtp_instance_get_remote_address(instance, &remote_address);
1814                 } else {
1815                         ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
1816                 }
1817
1818                 /* If we do not yet know an address to send this to defer it until we do */
1819                 if (ast_sockaddr_isnull(&remote_address)) {
1820                         return;
1821                 }
1822
1823                 out = BIO_read(dtls->write_bio, outgoing, sizeof(outgoing));
1824
1825                 /* Stop existing DTLS timer if running */
1826                 ast_mutex_lock(&rtp->dtls_timer_lock);
1827                 if (rtp->dtlstimerid > -1) {
1828                         AST_SCHED_DEL_UNREF(rtp->sched, rtp->dtlstimerid, ao2_ref(instance, -1));
1829                         rtp->dtlstimerid = -1;
1830                 }
1831
1832                 if (DTLSv1_get_timeout(dtls->ssl, &dtls_timeout)) {
1833                         int timeout = dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
1834                         ao2_ref(instance, +1);
1835                         if ((rtp->dtlstimerid = ast_sched_add(rtp->sched, timeout, dtls_srtp_handle_timeout, instance)) < 0) {
1836                                 ao2_ref(instance, -1);
1837                                 ast_log(LOG_WARNING, "scheduling DTLS retransmission for RTP instance [%p] failed.\n", instance);
1838                         }
1839                 }
1840                 ast_mutex_unlock(&rtp->dtls_timer_lock);
1841
1842                 __rtp_sendto(instance, outgoing, out, 0, &remote_address, rtcp, &ice, 0);
1843         }
1844 }
1845
1846 static int dtls_srtp_renegotiate(const void *data)
1847 {
1848         struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
1849         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1850
1851         SSL_renegotiate(rtp->dtls.ssl);
1852         SSL_do_handshake(rtp->dtls.ssl);
1853         dtls_srtp_check_pending(instance, rtp, 0);
1854
1855         if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
1856                 SSL_renegotiate(rtp->rtcp->dtls.ssl);
1857                 SSL_do_handshake(rtp->rtcp->dtls.ssl);
1858                 dtls_srtp_check_pending(instance, rtp, 1);
1859         }
1860
1861         rtp->rekeyid = -1;
1862         ao2_ref(instance, -1);
1863
1864         return 0;
1865 }
1866
1867 static int dtls_srtp_setup(struct ast_rtp *rtp, struct ast_srtp *srtp, struct ast_rtp_instance *instance)
1868 {
1869         unsigned char material[SRTP_MASTER_LEN * 2];
1870         unsigned char *local_key, *local_salt, *remote_key, *remote_salt;
1871         struct ast_srtp_policy *local_policy, *remote_policy = NULL;
1872         struct ast_rtp_instance_stats stats = { 0, };
1873         int res = -1;
1874
1875         /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
1876         if (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) {
1877                 X509 *certificate;
1878
1879                 if (!(certificate = SSL_get_peer_certificate(rtp->dtls.ssl))) {
1880                         ast_log(LOG_WARNING, "No certificate was provided by the peer on RTP instance '%p'\n", instance);
1881                         return -1;
1882                 }
1883
1884                 /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
1885                 if (rtp->remote_fingerprint[0]) {
1886                         const EVP_MD *type;
1887                         unsigned char fingerprint[EVP_MAX_MD_SIZE];
1888                         unsigned int size;
1889
1890                         if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA1) {
1891                                 type = EVP_sha1();
1892                         } else if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA256) {
1893                                 type = EVP_sha256();
1894                         } else {
1895                                 ast_log(LOG_WARNING, "Unsupported fingerprint hash type on RTP instance '%p'\n", instance);
1896                                 return -1;
1897                         }
1898
1899                         if (!X509_digest(certificate, type, fingerprint, &size) ||
1900                             !size ||
1901                             memcmp(fingerprint, rtp->remote_fingerprint, size)) {
1902                                 X509_free(certificate);
1903                                 ast_log(LOG_WARNING, "Fingerprint provided by remote party does not match that of peer certificate on RTP instance '%p'\n",
1904                                         instance);
1905                                 return -1;
1906                         }
1907                 }
1908
1909                 X509_free(certificate);
1910         }
1911
1912         /* Ensure that certificate verification was successful */
1913         if ((rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) && SSL_get_verify_result(rtp->dtls.ssl) != X509_V_OK) {
1914                 ast_log(LOG_WARNING, "Peer certificate on RTP instance '%p' failed verification test\n",
1915                         instance);
1916                 return -1;
1917         }
1918
1919         /* Produce key information and set up SRTP */
1920         if (!SSL_export_keying_material(rtp->dtls.ssl, material, SRTP_MASTER_LEN * 2, "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
1921                 ast_log(LOG_WARNING, "Unable to extract SRTP keying material from DTLS-SRTP negotiation on RTP instance '%p'\n",
1922                         instance);
1923                 return -1;
1924         }
1925
1926         /* Whether we are acting as a server or client determines where the keys/salts are */
1927         if (rtp->dtls.dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
1928                 local_key = material;
1929                 remote_key = local_key + SRTP_MASTER_KEY_LEN;
1930                 local_salt = remote_key + SRTP_MASTER_KEY_LEN;
1931                 remote_salt = local_salt + SRTP_MASTER_SALT_LEN;
1932         } else {
1933                 remote_key = material;
1934                 local_key = remote_key + SRTP_MASTER_KEY_LEN;
1935                 remote_salt = local_key + SRTP_MASTER_KEY_LEN;
1936                 local_salt = remote_salt + SRTP_MASTER_SALT_LEN;
1937         }
1938
1939         if (!(local_policy = res_srtp_policy->alloc())) {
1940                 return -1;
1941         }
1942
1943         if (res_srtp_policy->set_master_key(local_policy, local_key, SRTP_MASTER_KEY_LEN, local_salt, SRTP_MASTER_SALT_LEN) < 0) {
1944                 ast_log(LOG_WARNING, "Could not set key/salt information on local policy of '%p' when setting up DTLS-SRTP\n", rtp);
1945                 goto error;
1946         }
1947
1948         if (res_srtp_policy->set_suite(local_policy, rtp->suite)) {
1949                 ast_log(LOG_WARNING, "Could not set suite to '%u' on local policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
1950                 goto error;
1951         }
1952
1953         if (ast_rtp_instance_get_stats(instance, &stats, AST_RTP_INSTANCE_STAT_LOCAL_SSRC)) {
1954                 goto error;
1955         }
1956
1957         res_srtp_policy->set_ssrc(local_policy, stats.local_ssrc, 0);
1958
1959         if (!(remote_policy = res_srtp_policy->alloc())) {
1960                 goto error;
1961         }
1962
1963         if (res_srtp_policy->set_master_key(remote_policy, remote_key, SRTP_MASTER_KEY_LEN, remote_salt, SRTP_MASTER_SALT_LEN) < 0) {
1964                 ast_log(LOG_WARNING, "Could not set key/salt information on remote policy of '%p' when setting up DTLS-SRTP\n", rtp);
1965                 goto error;
1966         }
1967
1968         if (res_srtp_policy->set_suite(remote_policy, rtp->suite)) {
1969                 ast_log(LOG_WARNING, "Could not set suite to '%u' on remote policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
1970                 goto error;
1971         }
1972
1973         res_srtp_policy->set_ssrc(remote_policy, 0, 1);
1974
1975         if (ast_rtp_instance_add_srtp_policy(instance, remote_policy, local_policy)) {
1976                 ast_log(LOG_WARNING, "Could not set policies when setting up DTLS-SRTP on '%p'\n", rtp);
1977                 goto error;
1978         }
1979
1980         if (rtp->rekey) {
1981                 ao2_ref(instance, +1);
1982                 if ((rtp->rekeyid = ast_sched_add(rtp->sched, rtp->rekey * 1000, dtls_srtp_renegotiate, instance)) < 0) {
1983                         ao2_ref(instance, -1);
1984                         goto error;
1985                 }
1986         }
1987
1988         res = 0;
1989
1990 error:
1991         /* policy->destroy() called even on success to release local reference to these resources */
1992         res_srtp_policy->destroy(local_policy);
1993
1994         if (remote_policy) {
1995                 res_srtp_policy->destroy(remote_policy);
1996         }
1997
1998         return res;
1999 }
2000 #endif
2001
2002 static int __rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
2003 {
2004         int len;
2005         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2006         struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
2007         char *in = buf;
2008 #ifdef HAVE_PJPROJECT
2009         struct ast_sockaddr *loop = rtcp ? &rtp->rtcp_loop : &rtp->rtp_loop;
2010 #endif
2011
2012         if ((len = ast_recvfrom(rtcp ? rtp->rtcp->s : rtp->s, buf, size, flags, sa)) < 0) {
2013            return len;
2014         }
2015
2016 #ifdef HAVE_OPENSSL_SRTP
2017         dtls_srtp_check_pending(instance, rtp, rtcp);
2018
2019         /* If this is an SSL packet pass it to OpenSSL for processing. RFC section for first byte value:
2020          * https://tools.ietf.org/html/rfc5764#section-5.1.2 */
2021         if ((*in >= 20) && (*in <= 63)) {
2022                 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2023                 int res = 0;
2024
2025                 /* If no SSL session actually exists terminate things */
2026                 if (!dtls->ssl) {
2027                         ast_log(LOG_ERROR, "Received SSL traffic on RTP instance '%p' without an SSL session\n",
2028                                 instance);
2029                         return -1;
2030                 }
2031
2032                 /* If we don't yet know if we are active or passive and we receive a packet... we are obviously passive */
2033                 if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
2034                         dtls->dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
2035                         SSL_set_accept_state(dtls->ssl);
2036                 }
2037
2038                 dtls_srtp_check_pending(instance, rtp, rtcp);
2039
2040                 BIO_write(dtls->read_bio, buf, len);
2041
2042                 len = SSL_read(dtls->ssl, buf, len);
2043
2044                 if ((len < 0) && (SSL_get_error(dtls->ssl, len) == SSL_ERROR_SSL)) {
2045                         unsigned long error = ERR_get_error();
2046                         ast_log(LOG_ERROR, "DTLS failure occurred on RTP instance '%p' due to reason '%s', terminating\n",
2047                                 instance, ERR_reason_error_string(error));
2048                         return -1;
2049                 }
2050
2051                 dtls_srtp_check_pending(instance, rtp, rtcp);
2052
2053                 if (SSL_is_init_finished(dtls->ssl)) {
2054                         /* Any further connections will be existing since this is now established */
2055                         dtls->connection = AST_RTP_DTLS_CONNECTION_EXISTING;
2056                         if (!rtcp) {
2057                                 /* Use the keying material to set up key/salt information */
2058                                 res = dtls_srtp_setup(rtp, srtp, instance);
2059                         }
2060                 }
2061
2062                 return res;
2063         }
2064 #endif
2065
2066 #ifdef HAVE_PJPROJECT
2067         if (!ast_sockaddr_isnull(loop) && !ast_sockaddr_cmp(loop, sa)) {
2068                 /* ICE traffic will have been handled in the TURN callback, so skip it but update the address
2069                  * so it reflects the actual source and not the loopback
2070                  */
2071                 if (rtcp) {
2072                         ast_sockaddr_copy(sa, &rtp->rtcp->them);
2073                 } else {
2074                         ast_rtp_instance_get_remote_address(instance, sa);
2075                 }
2076         } else if (rtp->ice) {
2077                 pj_str_t combined = pj_str(ast_sockaddr_stringify(sa));
2078                 pj_sockaddr address;
2079                 pj_status_t status;
2080
2081                 pj_thread_register_check();
2082
2083                 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &combined, &address);
2084
2085                 status = pj_ice_sess_on_rx_pkt(rtp->ice, rtcp ? AST_RTP_ICE_COMPONENT_RTCP : AST_RTP_ICE_COMPONENT_RTP,
2086                         rtcp ? TRANSPORT_SOCKET_RTCP : TRANSPORT_SOCKET_RTP, buf, len, &address,
2087                         pj_sockaddr_get_len(&address));
2088                 if (status != PJ_SUCCESS) {
2089                         char buf[100];
2090
2091                         pj_strerror(status, buf, sizeof(buf));
2092                         ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
2093                                 (int)status, buf);
2094                         return -1;
2095                 }
2096                 if (!rtp->passthrough) {
2097                         return 0;
2098                 }
2099                 rtp->passthrough = 0;
2100         }
2101 #endif
2102
2103         if ((*in & 0xC0) && res_srtp && srtp && res_srtp->unprotect(srtp, buf, &len, rtcp) < 0) {
2104            return -1;
2105         }
2106
2107         return len;
2108 }
2109
2110 static int rtcp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
2111 {
2112         return __rtp_recvfrom(instance, buf, size, flags, sa, 1);
2113 }
2114
2115 static int rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
2116 {
2117         return __rtp_recvfrom(instance, buf, size, flags, sa, 0);
2118 }
2119
2120 static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *ice, int use_srtp)
2121 {
2122         int len = size;
2123         void *temp = buf;
2124         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2125         struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
2126
2127         *ice = 0;
2128
2129         if (use_srtp && res_srtp && srtp && res_srtp->protect(srtp, &temp, &len, rtcp) < 0) {
2130                 return -1;
2131         }
2132
2133 #ifdef HAVE_PJPROJECT
2134         if (rtp->ice) {
2135                 pj_thread_register_check();
2136
2137                 if (pj_ice_sess_send_data(rtp->ice, rtcp ? AST_RTP_ICE_COMPONENT_RTCP : AST_RTP_ICE_COMPONENT_RTP, temp, len) == PJ_SUCCESS) {
2138                         *ice = 1;
2139                         return len;
2140                 }
2141         }
2142 #endif
2143
2144         return ast_sendto(rtcp ? rtp->rtcp->s : rtp->s, temp, len, flags, sa);
2145 }
2146
2147 static int rtcp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
2148 {
2149         return __rtp_sendto(instance, buf, size, flags, sa, 1, ice, 1);
2150 }
2151
2152 static int rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
2153 {
2154         return __rtp_sendto(instance, buf, size, flags, sa, 0, ice, 1);
2155 }
2156
2157 static int rtp_get_rate(struct ast_format *format)
2158 {
2159         /* For those wondering: due to a fluke in RFC publication, G.722 is advertised
2160          * as having a sample rate of 8kHz, while implementations must know that its
2161          * real rate is 16kHz. Seriously.
2162          */
2163         return (ast_format_cmp(format, ast_format_g722) == AST_FORMAT_CMP_EQUAL) ? 8000 : (int)ast_format_get_sample_rate(format);
2164 }
2165
2166 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
2167 {
2168         unsigned int interval;
2169         /*! \todo XXX Do a more reasonable calculation on this one
2170          * Look in RFC 3550 Section A.7 for an example*/
2171         interval = rtcpinterval;
2172         return interval;
2173 }
2174
2175 /*! \brief Calculate normal deviation */
2176 static double normdev_compute(double normdev, double sample, unsigned int sample_count)
2177 {
2178         normdev = normdev * sample_count + sample;
2179         sample_count++;
2180
2181         return normdev / sample_count;
2182 }
2183
2184 static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
2185 {
2186 /*
2187                 for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
2188                 return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
2189                 we can compute the sigma^2 and that way we would have to do the sqrt only 1 time at the end and would save another pow 2 compute
2190                 optimized formula
2191 */
2192 #define SQUARE(x) ((x) * (x))
2193
2194         stddev = sample_count * stddev;
2195         sample_count++;
2196
2197         return stddev +
2198                 ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) +
2199                 ( SQUARE(sample - normdev_curent) / sample_count );
2200
2201 #undef SQUARE
2202 }
2203
2204 static int create_new_socket(const char *type, int af)
2205 {
2206         int sock = socket(af, SOCK_DGRAM, 0);
2207
2208         if (sock < 0) {
2209                 if (!type) {
2210                         type = "RTP/RTCP";
2211                 }
2212                 ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
2213         } else {
2214                 long flags = fcntl(sock, F_GETFL);
2215                 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
2216 #ifdef SO_NO_CHECK
2217                 if (nochecksums) {
2218                         setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
2219                 }
2220 #endif
2221         }
2222
2223         return sock;
2224 }
2225
2226 /*!
2227  * \internal
2228  * \brief Initializes sequence values and probation for learning mode.
2229  * \note This is an adaptation of pjmedia's pjmedia_rtp_seq_init function.
2230  *
2231  * \param info The learning information to track
2232  * \param seq sequence number read from the rtp header to initialize the information with
2233  */
2234 static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq)
2235 {
2236         info->max_seq = seq - 1;
2237         info->packets = learning_min_sequential;
2238 }
2239
2240 /*!
2241  * \internal
2242  * \brief Updates sequence information for learning mode and determines if probation/learning mode should remain in effect.
2243  * \note This function was adapted from pjmedia's pjmedia_rtp_seq_update function.
2244  *
2245  * \param info Structure tracking the learning progress of some address
2246  * \param seq sequence number read from the rtp header
2247  * \retval 0 if probation mode should exit for this address
2248  * \retval non-zero if probation mode should continue
2249  */
2250 static int rtp_learning_rtp_seq_update(struct rtp_learning_info *info, uint16_t seq)
2251 {
2252         if (seq == info->max_seq + 1) {
2253                 /* packet is in sequence */
2254                 info->packets--;
2255         } else {
2256                 /* Sequence discontinuity; reset */
2257                 info->packets = learning_min_sequential - 1;
2258         }
2259         info->max_seq = seq;
2260
2261         return (info->packets == 0);
2262 }
2263
2264 #ifdef HAVE_PJPROJECT
2265 static void rtp_add_candidates_to_ice(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_sockaddr *addr, int port, int component,
2266                                       int transport)
2267 {
2268         pj_sockaddr address[16];
2269         unsigned int count = PJ_ARRAY_SIZE(address), pos = 0;
2270
2271         /* Add all the local interface IP addresses */
2272         if (ast_sockaddr_is_ipv4(addr)) {
2273                 pj_enum_ip_interface(pj_AF_INET(), &count, address);
2274         } else if (ast_sockaddr_is_any(addr)) {
2275                 pj_enum_ip_interface(pj_AF_UNSPEC(), &count, address);
2276         } else {
2277                 pj_enum_ip_interface(pj_AF_INET6(), &count, address);
2278         }
2279
2280         for (pos = 0; pos < count; pos++) {
2281                 pj_sockaddr_set_port(&address[pos], port);
2282                 ast_rtp_ice_add_cand(rtp, component, transport, PJ_ICE_CAND_TYPE_HOST, 65535, &address[pos], &address[pos], NULL,
2283                                      pj_sockaddr_get_len(&address[pos]));
2284         }
2285
2286         /* If configured to use a STUN server to get our external mapped address do so */
2287         if (stunaddr.sin_addr.s_addr && ast_sockaddr_is_ipv4(addr) && count) {
2288                 struct sockaddr_in answer;
2289
2290                 if (!ast_stun_request(component == AST_RTP_ICE_COMPONENT_RTCP ? rtp->rtcp->s : rtp->s, &stunaddr, NULL, &answer)) {
2291                         pj_sockaddr base;
2292                         pj_str_t mapped = pj_str(ast_strdupa(ast_inet_ntoa(answer.sin_addr)));
2293
2294                         /* Use the first local host candidate as the base */
2295                         pj_sockaddr_cp(&base, &address[0]);
2296
2297                         pj_sockaddr_init(pj_AF_INET(), &address[0], &mapped, ntohs(answer.sin_port));
2298
2299                         ast_rtp_ice_add_cand(rtp, component, transport, PJ_ICE_CAND_TYPE_SRFLX, 65535, &address[0], &base,
2300                                              &base, pj_sockaddr_get_len(&address[0]));
2301                 }
2302         }
2303
2304         /* If configured to use a TURN relay create a session and allocate */
2305         if (pj_strlen(&turnaddr)) {
2306                 ast_rtp_ice_turn_request(instance, component, AST_TRANSPORT_TCP, pj_strbuf(&turnaddr), turnport,
2307                         pj_strbuf(&turnusername), pj_strbuf(&turnpassword));
2308         }
2309 }
2310 #endif
2311
2312 /*!
2313  * \internal
2314  * \brief Calculates the elapsed time from issue of the first tx packet in an
2315  *        rtp session and a specified time
2316  *
2317  * \param rtp pointer to the rtp struct with the transmitted rtp packet
2318  * \param delivery time of delivery - if NULL or zero value, will be ast_tvnow()
2319  *
2320  * \return time elapsed in milliseconds
2321  */
2322 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
2323 {
2324         struct timeval t;
2325         long ms;
2326
2327         if (ast_tvzero(rtp->txcore)) {
2328                 rtp->txcore = ast_tvnow();
2329                 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
2330         }
2331
2332         t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
2333         if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
2334                 ms = 0;
2335         }
2336         rtp->txcore = t;
2337
2338         return (unsigned int) ms;
2339 }
2340
2341 #ifdef HAVE_PJPROJECT
2342 /*!
2343  * \internal
2344  * \brief Creates an ICE session. Can be used to replace a destroyed ICE session.
2345  *
2346  * \param instance RTP instance for which the ICE session is being replaced
2347  * \param addr ast_sockaddr to use for adding RTP candidates to the ICE session
2348  * \param port port to use for adding RTP candidates to the ICE session
2349  * \param replace 0 when creating a new session, 1 when replacing a destroyed session
2350  *
2351  * \retval 0 on success
2352  * \retval -1 on failure
2353  */
2354 static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
2355         int port, int replace)
2356 {
2357         pj_stun_config stun_config;
2358         pj_str_t ufrag, passwd;
2359         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2360
2361         ao2_cleanup(rtp->ice_local_candidates);
2362         rtp->ice_local_candidates = NULL;
2363
2364         pj_thread_register_check();
2365
2366         pj_stun_config_init(&stun_config, &cachingpool.factory, 0, NULL, timer_heap);
2367
2368         ufrag = pj_str(rtp->local_ufrag);
2369         passwd = pj_str(rtp->local_passwd);
2370
2371         /* Create an ICE session for ICE negotiation */
2372         if (pj_ice_sess_create(&stun_config, NULL, PJ_ICE_SESS_ROLE_UNKNOWN, 2,
2373                         &ast_rtp_ice_sess_cb, &ufrag, &passwd, NULL, &rtp->ice) == PJ_SUCCESS) {
2374                 /* Make this available for the callbacks */
2375                 rtp->ice->user_data = instance;
2376
2377                 /* Add all of the available candidates to the ICE session */
2378                 rtp_add_candidates_to_ice(instance, rtp, addr, port, AST_RTP_ICE_COMPONENT_RTP,
2379                         TRANSPORT_SOCKET_RTP);
2380
2381                 /* Only add the RTCP candidates to ICE when replacing the session. New sessions
2382                  * handle this in a separate part of the setup phase */
2383                 if (replace && rtp->rtcp) {
2384                         rtp_add_candidates_to_ice(instance, rtp, &rtp->rtcp->us,
2385                                 ast_sockaddr_port(&rtp->rtcp->us), AST_RTP_ICE_COMPONENT_RTCP,
2386                                 TRANSPORT_SOCKET_RTCP);
2387                 }
2388
2389                 return 0;
2390         }
2391
2392         return -1;
2393
2394 }
2395 #endif
2396
2397 static int ast_rtp_new(struct ast_rtp_instance *instance,
2398                        struct ast_sched_context *sched, struct ast_sockaddr *addr,
2399                        void *data)
2400 {
2401         struct ast_rtp *rtp = NULL;
2402         int x, startplace;
2403
2404         /* Create a new RTP structure to hold all of our data */
2405         if (!(rtp = ast_calloc(1, sizeof(*rtp)))) {
2406                 return -1;
2407         }
2408
2409         /* Initialize synchronization aspects */
2410         ast_mutex_init(&rtp->lock);
2411         ast_cond_init(&rtp->cond, NULL);
2412
2413         /* Set default parameters on the newly created RTP structure */
2414         rtp->ssrc = ast_random();
2415         rtp->seqno = ast_random() & 0xffff;
2416         rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
2417         if (strictrtp) {
2418                 rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t)rtp->seqno);
2419                 rtp_learning_seq_init(&rtp->alt_source_learn, (uint16_t)rtp->seqno);
2420         }
2421
2422         /* Create a new socket for us to listen on and use */
2423         if ((rtp->s =
2424              create_new_socket("RTP",
2425                                ast_sockaddr_is_ipv4(addr) ? AF_INET  :
2426                                ast_sockaddr_is_ipv6(addr) ? AF_INET6 : -1)) < 0) {
2427                 ast_debug(1, "Failed to create a new socket for RTP instance '%p'\n", instance);
2428                 ast_free(rtp);
2429                 return -1;
2430         }
2431
2432         /* Now actually find a free RTP port to use */
2433         x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
2434         x = x & ~1;
2435         startplace = x;
2436
2437         for (;;) {
2438                 ast_sockaddr_set_port(addr, x);
2439                 /* Try to bind, this will tell us whether the port is available or not */
2440                 if (!ast_bind(rtp->s, addr)) {
2441                         ast_debug(1, "Allocated port %d for RTP instance '%p'\n", x, instance);
2442                         ast_rtp_instance_set_local_address(instance, addr);
2443                         break;
2444                 }
2445
2446                 x += 2;
2447                 if (x > rtpend) {
2448                         x = (rtpstart + 1) & ~1;
2449                 }
2450
2451                 /* See if we ran out of ports or if the bind actually failed because of something other than the address being in use */
2452                 if (x == startplace || (errno != EADDRINUSE && errno != EACCES)) {
2453                         ast_log(LOG_ERROR, "Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
2454                         close(rtp->s);
2455                         ast_free(rtp);
2456                         return -1;
2457                 }
2458         }
2459
2460 #ifdef HAVE_PJPROJECT
2461         generate_random_string(rtp->local_ufrag, sizeof(rtp->local_ufrag));
2462         generate_random_string(rtp->local_passwd, sizeof(rtp->local_passwd));
2463 #endif
2464         ast_rtp_instance_set_data(instance, rtp);
2465 #ifdef HAVE_PJPROJECT
2466         /* Create an ICE session for ICE negotiation */
2467         if (icesupport) {
2468                 if (ice_create(instance, addr, x, 0)) {
2469                         ast_log(LOG_NOTICE, "Failed to start ICE session\n");
2470                 } else {
2471                         rtp->ice_port = x;
2472                         ast_sockaddr_copy(&rtp->ice_original_rtp_addr, addr);
2473                 }
2474         }
2475 #endif
2476
2477         /* Record any information we may need */
2478         rtp->sched = sched;
2479
2480 #ifdef HAVE_OPENSSL_SRTP
2481         rtp->rekeyid = -1;
2482         rtp->dtlstimerid = -1;
2483 #endif
2484
2485         rtp->f.subclass.format = ao2_bump(ast_format_none);
2486         rtp->lastrxformat = ao2_bump(ast_format_none);
2487         rtp->lasttxformat = ao2_bump(ast_format_none);
2488
2489         return 0;
2490 }
2491
2492 static int ast_rtp_destroy(struct ast_rtp_instance *instance)
2493 {
2494         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2495 #ifdef HAVE_PJPROJECT
2496         struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
2497         struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
2498 #endif
2499
2500         /* Destroy the smoother that was smoothing out audio if present */
2501         if (rtp->smoother) {
2502                 ast_smoother_free(rtp->smoother);
2503         }
2504
2505         /* Close our own socket so we no longer get packets */
2506         if (rtp->s > -1) {
2507                 close(rtp->s);
2508         }
2509
2510         /* Destroy RTCP if it was being used */
2511         if (rtp->rtcp) {
2512                 /*
2513                  * It is not possible for there to be an active RTCP scheduler
2514                  * entry at this point since it holds a reference to the
2515                  * RTP instance while it's active.
2516                  */
2517                 close(rtp->rtcp->s);
2518 #ifdef HAVE_OPENSSL_SRTP
2519                 if (rtp->rtcp->dtls.ssl) {
2520                         SSL_free(rtp->rtcp->dtls.ssl);
2521                 }
2522 #endif
2523                 ast_free(rtp->rtcp);
2524         }
2525
2526         /* Destroy RED if it was being used */
2527         if (rtp->red) {
2528                 AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
2529                 ast_free(rtp->red);
2530         }
2531
2532 #ifdef HAVE_PJPROJECT
2533         pj_thread_register_check();
2534
2535         /* Destroy the RTP TURN relay if being used */
2536         ast_mutex_lock(&rtp->lock);
2537         if (rtp->turn_rtp) {
2538                 pj_turn_sock_destroy(rtp->turn_rtp);
2539                 rtp->turn_state = PJ_TURN_STATE_NULL;
2540                 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
2541                         ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
2542                 }
2543         }
2544
2545         /* Destroy the RTCP TURN relay if being used */
2546         if (rtp->turn_rtcp) {
2547                 pj_turn_sock_destroy(rtp->turn_rtcp);
2548                 rtp->turn_state = PJ_TURN_STATE_NULL;
2549                 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
2550                         ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
2551                 }
2552         }
2553         ast_mutex_unlock(&rtp->lock);
2554
2555         if (rtp->ioqueue) {
2556                 rtp_ioqueue_thread_remove(rtp->ioqueue);
2557         }
2558
2559         /* Destroy the ICE session if being used */
2560         if (rtp->ice) {
2561                 pj_ice_sess_destroy(rtp->ice);
2562         }
2563
2564         /* Destroy any candidates */
2565         if (rtp->ice_local_candidates) {
2566                 ao2_ref(rtp->ice_local_candidates, -1);
2567         }
2568
2569         if (rtp->ice_active_remote_candidates) {
2570                 ao2_ref(rtp->ice_active_remote_candidates, -1);
2571         }
2572 #endif
2573
2574 #ifdef HAVE_OPENSSL_SRTP
2575         /* Destroy the SSL context if present */
2576         if (rtp->ssl_ctx) {
2577                 SSL_CTX_free(rtp->ssl_ctx);
2578         }
2579
2580         /* Destroy the SSL session if present */
2581         if (rtp->dtls.ssl) {
2582                 SSL_free(rtp->dtls.ssl);
2583         }
2584 #endif
2585
2586         ao2_cleanup(rtp->lasttxformat);
2587         ao2_cleanup(rtp->lastrxformat);
2588         ao2_cleanup(rtp->f.subclass.format);
2589
2590         /* Destroy synchronization items */
2591         ast_mutex_destroy(&rtp->lock);
2592         ast_cond_destroy(&rtp->cond);
2593
2594         /* Finally destroy ourselves */
2595         ast_free(rtp);
2596
2597         return 0;
2598 }
2599
2600 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
2601 {
2602         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2603         rtp->dtmfmode = dtmf_mode;
2604         return 0;
2605 }
2606
2607 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance)
2608 {
2609         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2610         return rtp->dtmfmode;
2611 }
2612
2613 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
2614 {
2615         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2616         struct ast_sockaddr remote_address = { {0,} };
2617         int hdrlen = 12, res = 0, i = 0, payload = 101;
2618         char data[256];
2619         unsigned int *rtpheader = (unsigned int*)data;
2620
2621         ast_rtp_instance_get_remote_address(instance, &remote_address);
2622
2623         /* If we have no remote address information bail out now */
2624         if (ast_sockaddr_isnull(&remote_address)) {
2625                 return -1;
2626         }
2627
2628         /* Convert given digit into what we want to transmit */
2629         if ((digit <= '9') && (digit >= '0')) {
2630                 digit -= '0';
2631         } else if (digit == '*') {
2632                 digit = 10;
2633         } else if (digit == '#') {
2634                 digit = 11;
2635         } else if ((digit >= 'A') && (digit <= 'D')) {
2636                 digit = digit - 'A' + 12;
2637         } else if ((digit >= 'a') && (digit <= 'd')) {
2638                 digit = digit - 'a' + 12;
2639         } else {
2640                 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2641                 return -1;
2642         }
2643
2644         /* Grab the payload that they expect the RFC2833 packet to be received in */
2645         payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, NULL, AST_RTP_DTMF);
2646
2647         rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2648         rtp->send_duration = 160;
2649         rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
2650         rtp->lastdigitts = rtp->lastts + rtp->send_duration;
2651
2652         /* Create the actual packet that we will be sending */
2653         rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
2654         rtpheader[1] = htonl(rtp->lastdigitts);
2655         rtpheader[2] = htonl(rtp->ssrc);
2656
2657         /* Actually send the packet */
2658         for (i = 0; i < 2; i++) {
2659                 int ice;
2660
2661                 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2662                 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
2663                 if (res < 0) {
2664                         ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
2665                                 ast_sockaddr_stringify(&remote_address),
2666                                 strerror(errno));
2667                 }
2668                 if (rtp_debug_test_addr(&remote_address)) {
2669                         ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
2670                                     ast_sockaddr_stringify(&remote_address),
2671                                     ice ? " (via ICE)" : "",
2672                                     payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2673                 }
2674                 rtp->seqno++;
2675                 rtp->send_duration += 160;
2676                 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
2677         }
2678
2679         /* Record that we are in the process of sending a digit and information needed to continue doing so */
2680         rtp->sending_digit = 1;
2681         rtp->send_digit = digit;
2682         rtp->send_payload = payload;
2683
2684         return 0;
2685 }
2686
2687 static int ast_rtp_dtmf_continuation(struct ast_rtp_instance *instance)
2688 {
2689         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2690         struct ast_sockaddr remote_address = { {0,} };
2691         int hdrlen = 12, res = 0;
2692         char data[256];
2693         unsigned int *rtpheader = (unsigned int*)data;
2694         int ice;
2695
2696         ast_rtp_instance_get_remote_address(instance, &remote_address);
2697
2698         /* Make sure we know where the other side is so we can send them the packet */
2699         if (ast_sockaddr_isnull(&remote_address)) {
2700                 return -1;
2701         }
2702
2703         /* Actually create the packet we will be sending */
2704         rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2705         rtpheader[1] = htonl(rtp->lastdigitts);
2706         rtpheader[2] = htonl(rtp->ssrc);
2707         rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
2708
2709         /* Boom, send it on out */
2710         res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
2711         if (res < 0) {
2712                 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
2713                         ast_sockaddr_stringify(&remote_address),
2714                         strerror(errno));
2715         }
2716
2717         if (rtp_debug_test_addr(&remote_address)) {
2718                 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
2719                             ast_sockaddr_stringify(&remote_address),
2720                             ice ? " (via ICE)" : "",
2721                             rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2722         }
2723
2724         /* And now we increment some values for the next time we swing by */
2725         rtp->seqno++;
2726         rtp->send_duration += 160;
2727         rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
2728
2729         return 0;
2730 }
2731
2732 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
2733 {
2734         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2735         struct ast_sockaddr remote_address = { {0,} };
2736         int hdrlen = 12, res = -1, i = 0;
2737         char data[256];
2738         unsigned int *rtpheader = (unsigned int*)data;
2739         unsigned int measured_samples;
2740
2741         ast_rtp_instance_get_remote_address(instance, &remote_address);
2742
2743         /* Make sure we know where the remote side is so we can send them the packet we construct */
2744         if (ast_sockaddr_isnull(&remote_address)) {
2745                 goto cleanup;
2746         }
2747
2748         /* Convert the given digit to the one we are going to send */
2749         if ((digit <= '9') && (digit >= '0')) {
2750                 digit -= '0';
2751         } else if (digit == '*') {
2752                 digit = 10;
2753         } else if (digit == '#') {
2754                 digit = 11;
2755         } else if ((digit >= 'A') && (digit <= 'D')) {
2756                 digit = digit - 'A' + 12;
2757         } else if ((digit >= 'a') && (digit <= 'd')) {
2758                 digit = digit - 'a' + 12;
2759         } else {
2760                 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2761                 goto cleanup;
2762         }
2763
2764         rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2765
2766         if (duration > 0 && (measured_samples = duration * rtp_get_rate(rtp->f.subclass.format) / 1000) > rtp->send_duration) {
2767                 ast_debug(2, "Adjusting final end duration from %d to %u\n", rtp->send_duration, measured_samples);
2768                 rtp->send_duration = measured_samples;
2769         }
2770
2771         /* Construct the packet we are going to send */
2772         rtpheader[1] = htonl(rtp->lastdigitts);
2773         rtpheader[2] = htonl(rtp->ssrc);
2774         rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2775         rtpheader[3] |= htonl((1 << 23));
2776
2777         /* Send it 3 times, that's the magical number */
2778         for (i = 0; i < 3; i++) {
2779                 int ice;
2780
2781                 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2782
2783                 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
2784
2785                 if (res < 0) {
2786                         ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
2787                                 ast_sockaddr_stringify(&remote_address),
2788                                 strerror(errno));
2789                 }
2790
2791                 if (rtp_debug_test_addr(&remote_address)) {
2792                         ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
2793                                     ast_sockaddr_stringify(&remote_address),
2794                                     ice ? " (via ICE)" : "",
2795                                     rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2796                 }
2797
2798                 rtp->seqno++;
2799         }
2800         res = 0;
2801
2802         /* Oh and we can't forget to turn off the stuff that says we are sending DTMF */
2803         rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
2804 cleanup:
2805         rtp->sending_digit = 0;
2806         rtp->send_digit = 0;
2807
2808         return res;
2809 }
2810
2811 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
2812 {
2813         return ast_rtp_dtmf_end_with_duration(instance, digit, 0);
2814 }
2815
2816 static void ast_rtp_update_source(struct ast_rtp_instance *instance)
2817 {
2818         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2819
2820         /* We simply set this bit so that the next packet sent will have the marker bit turned on */
2821         ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
2822         ast_debug(3, "Setting the marker bit due to a source update\n");
2823
2824         return;
2825 }
2826
2827 static void ast_rtp_change_source(struct ast_rtp_instance *instance)
2828 {
2829         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2830         struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
2831         unsigned int ssrc = ast_random();
2832
2833         if (!rtp->lastts) {
2834                 ast_debug(3, "Not changing SSRC since we haven't sent any RTP yet\n");
2835                 return;
2836         }
2837
2838         /* We simply set this bit so that the next packet sent will have the marker bit turned on */
2839         ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
2840
2841         ast_debug(3, "Changing ssrc from %u to %u due to a source change\n", rtp->ssrc, ssrc);
2842
2843         if (srtp) {
2844                 ast_debug(3, "Changing ssrc for SRTP from %u to %u\n", rtp->ssrc, ssrc);
2845                 res_srtp->change_source(srtp, rtp->ssrc, ssrc);
2846         }
2847
2848         rtp->ssrc = ssrc;
2849
2850         return;
2851 }
2852
2853 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
2854 {
2855         unsigned int sec, usec, frac;
2856         sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
2857         usec = tv.tv_usec;
2858         frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
2859         *msw = sec;
2860         *lsw = frac;
2861 }
2862
2863 static void ntp2timeval(unsigned int msw, unsigned int lsw, struct timeval *tv)
2864 {
2865         tv->tv_sec = msw - 2208988800u;
2866         tv->tv_usec = ((lsw << 6) / 3650) - (lsw >> 12) - (lsw >> 8);
2867 }
2868
2869 static void calculate_lost_packet_statistics(struct ast_rtp *rtp,
2870                 unsigned int *lost_packets,
2871                 int *fraction_lost)
2872 {
2873         unsigned int extended_seq_no;
2874         unsigned int expected_packets;
2875         unsigned int expected_interval;
2876         unsigned int received_interval;
2877         double rxlost_current;
2878         int lost_interval;
2879
2880         /* Compute statistics */
2881         extended_seq_no = rtp->cycles + rtp->lastrxseqno;
2882         expected_packets = extended_seq_no - rtp->seedrxseqno + 1;
2883         if (rtp->rxcount > expected_packets) {
2884                 expected_packets += rtp->rxcount - expected_packets;
2885         }
2886         *lost_packets = expected_packets - rtp->rxcount;
2887         expected_interval = expected_packets - rtp->rtcp->expected_prior;
2888         received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2889         lost_interval = expected_interval - received_interval;
2890         if (expected_interval == 0 || lost_interval <= 0) {
2891                 *fraction_lost = 0;
2892         } else {
2893                 *fraction_lost = (lost_interval << 8) / expected_interval;
2894         }
2895
2896         /* Update RTCP statistics */
2897         rtp->rtcp->received_prior = rtp->rxcount;
2898         rtp->rtcp->expected_prior = expected_packets;
2899         if (lost_interval <= 0) {
2900                 rtp->rtcp->rxlost = 0;
2901         } else {
2902                 rtp->rtcp->rxlost = lost_interval;
2903         }
2904         if (rtp->rtcp->rxlost_count == 0) {
2905                 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
2906         }
2907         if (lost_interval < rtp->rtcp->minrxlost) {
2908                 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
2909         }
2910         if (lost_interval > rtp->rtcp->maxrxlost) {
2911                 rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
2912         }
2913         rxlost_current = normdev_compute(rtp->rtcp->normdev_rxlost,
2914                         rtp->rtcp->rxlost,
2915                         rtp->rtcp->rxlost_count);
2916         rtp->rtcp->stdev_rxlost = stddev_compute(rtp->rtcp->stdev_rxlost,
2917                         rtp->rtcp->rxlost,
2918                         rtp->rtcp->normdev_rxlost,
2919                         rxlost_current,
2920                         rtp->rtcp->rxlost_count);
2921         rtp->rtcp->normdev_rxlost = rxlost_current;
2922         rtp->rtcp->rxlost_count++;
2923 }
2924
2925 /*! \brief Send RTCP SR or RR report */
2926 static int ast_rtcp_write_report(struct ast_rtp_instance *instance, int sr)
2927 {
2928         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2929         RAII_VAR(struct ast_json *, message_blob, NULL, ast_json_unref);
2930         int res;
2931         int len = 0;
2932         struct timeval now;
2933         unsigned int now_lsw;
2934         unsigned int now_msw;
2935         unsigned int *rtcpheader;
2936         unsigned int lost_packets;
2937         int fraction_lost;
2938         struct timeval dlsr = { 0, };
2939         char bdata[512];
2940         int rate = rtp_get_rate(rtp->f.subclass.format);
2941         int ice;
2942         int header_offset = 0;
2943         char *str_remote_address;
2944         char *str_local_address;
2945         struct ast_sockaddr remote_address = { { 0, } };
2946         struct ast_sockaddr local_address = { { 0, } };
2947         struct ast_sockaddr real_remote_address = { { 0, } };
2948         struct ast_sockaddr real_local_address = { { 0, } };
2949         struct ast_rtp_rtcp_report_block *report_block = NULL;
2950         RAII_VAR(struct ast_rtp_rtcp_report *, rtcp_report,
2951                         ast_rtp_rtcp_report_alloc(rtp->themssrc ? 1 : 0),
2952                         ao2_cleanup);
2953
2954         if (!rtp || !rtp->rtcp) {
2955                 return 0;
2956         }
2957
2958         if (ast_sockaddr_isnull(&rtp->rtcp->them)) {  /* This'll stop rtcp for this rtp session */
2959                 /* RTCP was stopped. */
2960                 return 0;
2961         }
2962
2963         if (!rtcp_report) {
2964                 return 1;
2965         }
2966
2967         /* Compute statistics */
2968         calculate_lost_packet_statistics(rtp, &lost_packets, &fraction_lost);
2969
2970         gettimeofday(&now, NULL);
2971         rtcp_report->reception_report_count = rtp->themssrc ? 1 : 0;
2972         rtcp_report->ssrc = rtp->ssrc;
2973         rtcp_report->type = sr ? RTCP_PT_SR : RTCP_PT_RR;
2974         if (sr) {
2975                 rtcp_report->sender_information.ntp_timestamp = now;
2976                 rtcp_report->sender_information.rtp_timestamp = rtp->lastts;
2977                 rtcp_report->sender_information.packet_count = rtp->txcount;
2978                 rtcp_report->sender_information.octet_count = rtp->txoctetcount;
2979         }
2980
2981         if (rtp->themssrc) {
2982                 report_block = ast_calloc(1, sizeof(*report_block));
2983                 if (!report_block) {
2984                         return 1;
2985                 }
2986
2987                 rtcp_report->report_block[0] = report_block;
2988                 report_block->source_ssrc = rtp->themssrc;
2989                 report_block->lost_count.fraction = (fraction_lost & 0xff);
2990                 report_block->lost_count.packets = (lost_packets & 0xffffff);
2991                 report_block->highest_seq_no = (rtp->cycles | (rtp->lastrxseqno & 0xffff));
2992                 report_block->ia_jitter = (unsigned int)(rtp->rxjitter * rate);
2993                 report_block->lsr = rtp->rtcp->themrxlsr;
2994                 /* If we haven't received an SR report, DLSR should be 0 */
2995                 if (!ast_tvzero(rtp->rtcp->rxlsr)) {
2996                         timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2997                         report_block->dlsr = (((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000;
2998                 }
2999         }
3000         timeval2ntp(rtcp_report->sender_information.ntp_timestamp, &now_msw, &now_lsw);
3001         rtcpheader = (unsigned int *)bdata;
3002         rtcpheader[1] = htonl(rtcp_report->ssrc);            /* Our SSRC */
3003         len += 8;
3004         if (sr) {
3005                 header_offset = 5;
3006                 rtcpheader[2] = htonl(now_msw);                 /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
3007                 rtcpheader[3] = htonl(now_lsw);                 /* now, LSW */
3008                 rtcpheader[4] = htonl(rtcp_report->sender_information.rtp_timestamp);
3009                 rtcpheader[5] = htonl(rtcp_report->sender_information.packet_count);
3010                 rtcpheader[6] = htonl(rtcp_report->sender_information.octet_count);
3011                 len += 20;
3012         }
3013         if (report_block) {
3014                 rtcpheader[2 + header_offset] = htonl(report_block->source_ssrc);     /* Their SSRC */
3015                 rtcpheader[3 + header_offset] = htonl((report_block->lost_count.fraction << 24) | report_block->lost_count.packets);
3016                 rtcpheader[4 + header_offset] = htonl(report_block->highest_seq_no);
3017                 rtcpheader[5 + header_offset] = htonl(report_block->ia_jitter);
3018                 rtcpheader[6 + header_offset] = htonl(report_block->lsr);
3019                 rtcpheader[7 + header_offset] = htonl(report_block->dlsr);
3020                 len += 24;
3021         }
3022         rtcpheader[0] = htonl((2 << 30) | (rtcp_report->reception_report_count << 24)
3023                                         | ((sr ? RTCP_PT_SR : RTCP_PT_RR) << 16) | ((len/4)-1));
3024
3025         /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
3026         /* it can change mid call, and SDES can't) */
3027         rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
3028         rtcpheader[(len/4)+1] = htonl(rtcp_report->ssrc);
3029         rtcpheader[(len/4)+2] = htonl(0x01 << 24);
3030         len += 12;
3031
3032         ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
3033         res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &remote_address, &ice);
3034         if (res < 0) {
3035                 ast_log(LOG_ERROR, "RTCP %s transmission error to %s, rtcp halted %s\n",
3036                         sr ? "SR" : "RR",
3037                         ast_sockaddr_stringify(&rtp->rtcp->them),
3038                         strerror(errno));
3039                 return 0;
3040         }
3041
3042         /* Update RTCP SR/RR statistics */
3043         if (sr) {
3044                 rtp->rtcp->txlsr = rtcp_report->sender_information.ntp_timestamp;
3045                 rtp->rtcp->sr_count++;
3046                 rtp->rtcp->lastsrtxcount = rtp->txcount;
3047         } else {
3048                 rtp->rtcp->rr_count++;
3049         }
3050
3051         if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
3052                 ast_verbose("* Sent RTCP %s to %s%s\n", sr ? "SR" : "RR",
3053                                 ast_sockaddr_stringify(&remote_address), ice ? " (via ICE)" : "");
3054                 ast_verbose("  Our SSRC: %u\n", rtcp_report->ssrc);
3055                 if (sr) {
3056                         ast_verbose("  Sent(NTP): %u.%010u\n",
3057                                 (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_sec,
3058                                 (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_usec * 4096);
3059                         ast_verbose("  Sent(RTP): %u\n", rtcp_report->sender_information.rtp_timestamp);
3060                         ast_verbose("  Sent packets: %u\n", rtcp_report->sender_information.packet_count);
3061                         ast_verbose("  Sent octets: %u\n", rtcp_report->sender_information.octet_count);
3062                 }
3063                 if (report_block) {
3064                         ast_verbose("  Report block:\n");
3065                         ast_verbose("    Their SSRC: %u\n", report_block->source_ssrc);
3066                         ast_verbose("    Fraction lost: %d\n", report_block->lost_count.fraction);
3067                         ast_verbose("    Cumulative loss: %u\n", report_block->lost_count.packets);
3068                         ast_verbose("    Highest seq no: %u\n", report_block->highest_seq_no);
3069                         ast_verbose("    IA jitter: %.4f\n", (double)report_block->ia_jitter / rate);
3070                         ast_verbose("    Their last SR: %u\n", report_block->lsr);
3071                         ast_verbose("    DLSR: %4.4f (sec)\n\n", (double)(report_block->dlsr / 65536.0));
3072                 }
3073         }
3074
3075         ast_rtp_instance_get_local_address(instance, &local_address);
3076         if (!ast_find_ourip(&real_local_address, &local_address, 0)) {
3077                 str_local_address = ast_strdupa(ast_sockaddr_stringify(&real_local_address));
3078         } else {
3079                 str_local_address = ast_strdupa(ast_sockaddr_stringify(&local_address));
3080         }
3081
3082         if (!ast_find_ourip(&real_remote_address, &remote_address, 0)) {
3083                 str_remote_address = ast_strdupa(ast_sockaddr_stringify(&real_remote_address));
3084         } else {
3085                 str_remote_address = ast_strdupa(ast_sockaddr_stringify(&remote_address));
3086         }
3087
3088         message_blob = ast_json_pack("{s: s, s: s}",
3089                         "to", str_remote_address,
3090                         "from", str_local_address);
3091         ast_rtp_publish_rtcp_message(instance, ast_rtp_rtcp_sent_type(),
3092                         rtcp_report,
3093                         message_blob);
3094         return res;
3095 }
3096
3097 /*! \brief Write and RTCP packet to the far end
3098  * \note Decide if we are going to send an SR (with Reception Block) or RR
3099  * RR is sent if we have not sent any rtp packets in the previous interval */
3100 static int ast_rtcp_write(const void *data)
3101 {
3102         struct ast_rtp_instance *instance = (struct ast_rtp_instance *) data;
3103         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3104         int res;
3105
3106         if (!rtp || !rtp->rtcp || rtp->rtcp->schedid == -1) {
3107                 ao2_ref(instance, -1);
3108                 return 0;
3109         }
3110
3111         if (rtp->txcount > rtp->rtcp->lastsrtxcount) {
3112                 /* Send an SR */
3113                 res = ast_rtcp_write_report(instance, 1);
3114         } else {
3115                 /* Send an RR */
3116                 res = ast_rtcp_write_report(instance, 0);
3117         }
3118
3119         if (!res) {
3120                 /*
3121                  * Not being rescheduled.
3122                  */
3123                 ao2_ref(instance, -1);
3124                 rtp->rtcp->schedid = -1;
3125         }
3126
3127         return res;
3128 }
3129
3130 static int ast_rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
3131 {
3132         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3133         int pred, mark = 0;
3134         unsigned int ms = calc_txstamp(rtp, &frame->delivery);
3135         struct ast_sockaddr remote_address = { {0,} };
3136         int rate = rtp_get_rate(frame->subclass.format) / 1000;
3137
3138         if (ast_format_cmp(frame->subclass.format, ast_format_g722) == AST_FORMAT_CMP_EQUAL) {
3139                 frame->samples /= 2;
3140         }
3141
3142         if (rtp->sending_digit) {
3143                 return 0;
3144         }
3145
3146         if (frame->frametype == AST_FRAME_VOICE) {
3147                 pred = rtp->lastts + frame->samples;
3148
3149                 /* Re-calculate last TS */
3150                 rtp->lastts = rtp->lastts + ms * rate;
3151                 if (ast_tvzero(frame->delivery)) {
3152                         /* If this isn't an absolute delivery time, Check if it is close to our prediction,
3153                            and if so, go with our prediction */
3154                         if (abs((int)rtp->lastts - pred) < MAX_TIMESTAMP_SKEW) {
3155                                 rtp->lastts = pred;
3156                         } else {
3157                                 ast_debug(3, "Difference is %d, ms is %u\n", abs((int)rtp->lastts - pred), ms);
3158                                 mark = 1;
3159                         }
3160                 }
3161         } else if (frame->frametype == AST_FRAME_VIDEO) {
3162                 mark = frame->subclass.frame_ending;
3163                 pred = rtp->lastovidtimestamp + frame->samples;
3164                 /* Re-calculate last TS */
3165                 rtp->lastts = rtp->lastts + ms * 90;
3166                 /* If it's close to our prediction, go for it */
3167                 if (ast_tvzero(frame->delivery)) {
3168                         if (abs((int)rtp->lastts - pred) < 7200) {
3169                                 rtp->lastts = pred;
3170                                 rtp->lastovidtimestamp += frame->samples;
3171                         } else {
3172                                 ast_debug(3, "Difference is %d, ms is %u (%u), pred/ts/samples %u/%d/%d\n", abs((int)rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, frame->samples);
3173                                 rtp->lastovidtimestamp = rtp->lastts;
3174                         }
3175                 }
3176         } else {
3177                 pred = rtp->lastotexttimestamp + frame->samples;
3178                 /* Re-calculate last TS */
3179                 rtp->lastts = rtp->lastts + ms;
3180                 /* If it's close to our prediction, go for it */
3181                 if (ast_tvzero(frame->delivery)) {
3182                         if (abs((int)rtp->lastts - pred) < 7200) {
3183                                 rtp->lastts = pred;
3184                                 rtp->lastotexttimestamp += frame->samples;
3185                         } else {
3186                                 ast_debug(3, "Difference is %d, ms is %u, pred/ts/samples %u/%d/%d\n", abs((int)rtp->lastts - pred), ms, rtp->lastts, pred, frame->samples);
3187                                 rtp->lastotexttimestamp = rtp->lastts;
3188                         }
3189                 }
3190         }
3191
3192         /* If we have been explicitly told to set the marker bit then do so */
3193         if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
3194                 mark = 1;
3195                 ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
3196         }
3197
3198         /* If the timestamp for non-digt packets has moved beyond the timestamp for digits, update the digit timestamp */
3199         if (rtp->lastts > rtp->lastdigitts) {
3200                 rtp->lastdigitts = rtp->lastts;
3201         }
3202
3203         if (ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO)) {
3204                 rtp->lastts = frame->ts * rate;
3205         }
3206
3207         ast_rtp_instance_get_remote_address(instance, &remote_address);
3208
3209         /* If we know the remote address construct a packet and send it out */
3210         if (!ast_sockaddr_isnull(&remote_address)) {
3211                 int hdrlen = 12, res, ice;
3212                 unsigned char *rtpheader = (unsigned char *)(frame->data.ptr - hdrlen);
3213
3214                 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
3215                 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
3216                 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
3217
3218                 if ((res = rtp_sendto(instance, (void *)rtpheader, frame->datalen + hdrlen, 0, &remote_address, &ice)) < 0) {
3219                         if (!ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT) || (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT) && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
3220                                 ast_debug(1, "RTP Transmission error of packet %d to %s: %s\n",
3221                                           rtp->seqno,
3222                                           ast_sockaddr_stringify(&remote_address),
3223                                           strerror(errno));
3224                         } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
3225                                 /* Only give this error message once if we are not RTP debugging */
3226                                 if (rtpdebug)