Sat Apr 26 2014 22:01:41

Asterisk developer's documentation


res_rtp_asterisk.c
Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2008, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*!
00020  * \file
00021  *
00022  * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
00023  *
00024  * \author Mark Spencer <markster@digium.com>
00025  *
00026  * \note RTP is defined in RFC 3550.
00027  *
00028  * \ingroup rtp_engines
00029  */
00030 
00031 /*** MODULEINFO
00032    <use type="external">uuid</use>
00033    <support_level>core</support_level>
00034  ***/
00035 
00036 #include "asterisk.h"
00037 
00038 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 409565 $")
00039 
00040 #include <sys/time.h>
00041 #include <signal.h>
00042 #include <fcntl.h>
00043 
00044 #ifdef HAVE_OPENSSL_SRTP
00045 #include <openssl/ssl.h>
00046 #include <openssl/err.h>
00047 #include <openssl/bio.h>
00048 #endif
00049 
00050 #ifdef USE_PJPROJECT
00051 /* Asterisk discourages the use of bzero in favor of memset, in fact if you try to use bzero it will tell you to use memset. As a result bzero has to be undefined
00052  * here since it is used internally by pjlib. The only other option would be to modify pjlib... which won't happen. */
00053 #undef bzero
00054 #define bzero bzero
00055 #include "pjlib.h"
00056 #include "pjlib-util.h"
00057 #include "pjnath.h"
00058 #endif
00059 
00060 #include "asterisk/stun.h"
00061 #include "asterisk/pbx.h"
00062 #include "asterisk/frame.h"
00063 #include "asterisk/channel.h"
00064 #include "asterisk/acl.h"
00065 #include "asterisk/config.h"
00066 #include "asterisk/lock.h"
00067 #include "asterisk/utils.h"
00068 #include "asterisk/cli.h"
00069 #include "asterisk/manager.h"
00070 #include "asterisk/unaligned.h"
00071 #include "asterisk/module.h"
00072 #include "asterisk/rtp_engine.h"
00073 #include "asterisk/test.h"
00074 
00075 #define MAX_TIMESTAMP_SKEW 640
00076 
00077 #define RTP_SEQ_MOD     (1<<16)  /*!< A sequence number can't be more than 16 bits */
00078 #define RTCP_DEFAULT_INTERVALMS   5000 /*!< Default milli-seconds between RTCP reports we send */
00079 #define RTCP_MIN_INTERVALMS       500  /*!< Min milli-seconds between RTCP reports we send */
00080 #define RTCP_MAX_INTERVALMS       60000   /*!< Max milli-seconds between RTCP reports we send */
00081 
00082 #define DEFAULT_RTP_START 5000 /*!< Default port number to start allocating RTP ports from */
00083 #define DEFAULT_RTP_END 31000  /*!< Default maximum port number to end allocating RTP ports at */
00084 
00085 #define MINIMUM_RTP_PORT 1024 /*!< Minimum port number to accept */
00086 #define MAXIMUM_RTP_PORT 65535 /*!< Maximum port number to accept */
00087 
00088 #define DEFAULT_TURN_PORT 34780
00089 
00090 #define TURN_ALLOCATION_WAIT_TIME 2000
00091 
00092 #define RTCP_PT_FUR     192
00093 #define RTCP_PT_SR      200
00094 #define RTCP_PT_RR      201
00095 #define RTCP_PT_SDES    202
00096 #define RTCP_PT_BYE     203
00097 #define RTCP_PT_APP     204
00098 
00099 #define RTP_MTU      1200
00100 #define DTMF_SAMPLE_RATE_MS    8 /*!< DTMF samples per millisecond */
00101 
00102 #define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000)) /*!< samples */
00103 
00104 #define ZFONE_PROFILE_ID 0x505a
00105 
00106 #define DEFAULT_LEARNING_MIN_SEQUENTIAL 4
00107 
00108 #define SRTP_MASTER_KEY_LEN 16
00109 #define SRTP_MASTER_SALT_LEN 14
00110 #define SRTP_MASTER_LEN (SRTP_MASTER_KEY_LEN + SRTP_MASTER_SALT_LEN)
00111 
00112 enum strict_rtp_state {
00113    STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
00114    STRICT_RTP_LEARN,    /*! Accept next packet as source */
00115    STRICT_RTP_CLOSED,   /*! Drop all RTP packets not coming from source that was learned */
00116 };
00117 
00118 #define DEFAULT_STRICT_RTP STRICT_RTP_CLOSED
00119 #define DEFAULT_ICESUPPORT 1
00120 
00121 extern struct ast_srtp_res *res_srtp;
00122 extern struct ast_srtp_policy_res *res_srtp_policy;
00123 
00124 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
00125 
00126 static int rtpstart = DEFAULT_RTP_START;        /*!< First port for RTP sessions (set in rtp.conf) */
00127 static int rtpend = DEFAULT_RTP_END;         /*!< Last port for RTP sessions (set in rtp.conf) */
00128 static int rtpdebug;       /*!< Are we debugging? */
00129 static int rtcpdebug;         /*!< Are we debugging RTCP? */
00130 static int rtcpstats;         /*!< Are we debugging RTCP? */
00131 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
00132 static struct ast_sockaddr rtpdebugaddr;  /*!< Debug packets to/from this host */
00133 static struct ast_sockaddr rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
00134 static int rtpdebugport;      /*< Debug only RTP packets from IP or IP+Port if port is > 0 */
00135 static int rtcpdebugport;     /*< Debug only RTCP packets from IP or IP+Port if port is > 0 */
00136 #ifdef SO_NO_CHECK
00137 static int nochecksums;
00138 #endif
00139 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. */
00140 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. */
00141 static int icesupport = DEFAULT_ICESUPPORT;
00142 static struct sockaddr_in stunaddr;
00143 
00144 #ifdef USE_PJPROJECT
00145 static pj_str_t turnaddr;
00146 static int turnport = DEFAULT_TURN_PORT;
00147 static pj_str_t turnusername;
00148 static pj_str_t turnpassword;
00149 
00150 /*! \brief Pool factory used by pjlib to allocate memory. */
00151 static pj_caching_pool cachingpool;
00152 
00153 /*! \brief Pool used by pjlib functions which require memory allocation. */
00154 static pj_pool_t *pool;
00155 
00156 /*! \brief I/O queue for TURN relay traffic */
00157 static pj_ioqueue_t *ioqueue;
00158 
00159 /*! \brief Timer heap for ICE and TURN stuff */
00160 static pj_timer_heap_t *timerheap;
00161 
00162 /*! \brief Worker thread for ICE/TURN */
00163 static pj_thread_t *thread;
00164 
00165 /*! \brief Notification that the ICE/TURN worker thread should stop */
00166 static int worker_terminate;
00167 #endif
00168 
00169 #define FLAG_3389_WARNING               (1 << 0)
00170 #define FLAG_NAT_ACTIVE                 (3 << 1)
00171 #define FLAG_NAT_INACTIVE               (0 << 1)
00172 #define FLAG_NAT_INACTIVE_NOWARN        (1 << 1)
00173 #define FLAG_NEED_MARKER_BIT            (1 << 3)
00174 #define FLAG_DTMF_COMPENSATE            (1 << 4)
00175 
00176 #define TRANSPORT_SOCKET_RTP 1
00177 #define TRANSPORT_SOCKET_RTCP 2
00178 #define TRANSPORT_TURN_RTP 3
00179 #define TRANSPORT_TURN_RTCP 4
00180 
00181 /*! \brief RTP learning mode tracking information */
00182 struct rtp_learning_info {
00183    int max_seq;   /*!< The highest sequence number received */
00184    int packets;   /*!< The number of remaining packets before the source is accepted */
00185 };
00186 
00187 /*! \brief RTP session description */
00188 struct ast_rtp {
00189    int s;
00190    struct ast_frame f;
00191    unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
00192    unsigned int ssrc;      /*!< Synchronization source, RFC 3550, page 10. */
00193    unsigned int themssrc;     /*!< Their SSRC */
00194    unsigned int rxssrc;
00195    unsigned int lastts;
00196    unsigned int lastrxts;
00197    unsigned int lastividtimestamp;
00198    unsigned int lastovidtimestamp;
00199    unsigned int lastitexttimestamp;
00200    unsigned int lastotexttimestamp;
00201    unsigned int lasteventseqn;
00202    int lastrxseqno;                /*!< Last received sequence number */
00203    unsigned short seedrxseqno;     /*!< What sequence number did they start with?*/
00204    unsigned int seedrxts;          /*!< What RTP timestamp did they start with? */
00205    unsigned int rxcount;           /*!< How many packets have we received? */
00206    unsigned int rxoctetcount;      /*!< How many octets have we received? should be rxcount *160*/
00207    unsigned int txcount;           /*!< How many packets have we sent? */
00208    unsigned int txoctetcount;      /*!< How many octets have we sent? (txcount*160)*/
00209    unsigned int cycles;            /*!< Shifted count of sequence number cycles */
00210    double rxjitter;                /*!< Interarrival jitter at the moment in seconds */
00211    double rxtransit;               /*!< Relative transit time for previous packet */
00212    struct ast_format lasttxformat;
00213    struct ast_format lastrxformat;
00214 
00215    int rtptimeout;         /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
00216    int rtpholdtimeout;     /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
00217    int rtpkeepalive;    /*!< Send RTP comfort noice packets for keepalive */
00218 
00219    /* DTMF Reception Variables */
00220    char resp;                        /*!< The current digit being processed */
00221    unsigned int last_seqno;          /*!< The last known sequence number for any DTMF packet */
00222    unsigned int last_end_timestamp;  /*!< The last known timestamp received from an END packet */
00223    unsigned int dtmf_duration;       /*!< Total duration in samples since the digit start event */
00224    unsigned int dtmf_timeout;        /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
00225    unsigned int dtmfsamples;
00226    enum ast_rtp_dtmf_mode dtmfmode;  /*!< The current DTMF mode of the RTP stream */
00227    /* DTMF Transmission Variables */
00228    unsigned int lastdigitts;
00229    char sending_digit;  /*!< boolean - are we sending digits */
00230    char send_digit;  /*!< digit we are sending */
00231    int send_payload;
00232    int send_duration;
00233    unsigned int flags;
00234    struct timeval rxcore;
00235    struct timeval txcore;
00236    double drxcore;                 /*!< The double representation of the first received packet */
00237    struct timeval lastrx;          /*!< timeval when we last received a packet */
00238    struct timeval dtmfmute;
00239    struct ast_smoother *smoother;
00240    int *ioid;
00241    unsigned short seqno;      /*!< Sequence number, RFC 3550, page 13. */
00242    unsigned short rxseqno;
00243    struct ast_sched_context *sched;
00244    struct io_context *io;
00245    void *data;
00246    struct ast_rtcp *rtcp;
00247    struct ast_rtp *bridged;        /*!< Who we are Packet bridged to */
00248 
00249    enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
00250    struct ast_sockaddr strict_rtp_address;  /*!< Remote address information for strict RTP purposes */
00251    struct ast_sockaddr alt_rtp_address; /*!<Alternate remote address information */
00252 
00253    /*
00254     * Learning mode values based on pjmedia's probation mode.  Many of these values are redundant to the above,
00255     * but these are in place to keep learning mode sequence values sealed from their normal counterparts.
00256     */
00257    struct rtp_learning_info rtp_source_learn;   /* Learning mode track for the expected RTP source */
00258    struct rtp_learning_info alt_source_learn;   /* Learning mode tracking for a new RTP source after one has been chosen */
00259 
00260    struct rtp_red *red;
00261 
00262 #ifdef USE_PJPROJECT
00263    pj_ice_sess *ice;           /*!< ICE session */
00264    pj_turn_sock *turn_rtp;     /*!< RTP TURN relay */
00265    pj_turn_sock *turn_rtcp;    /*!< RTCP TURN relay */
00266    ast_mutex_t lock;           /*!< Lock for synchronization purposes */
00267    pj_turn_state_t turn_state; /*!< Current state of the TURN relay session */
00268    ast_cond_t cond;            /*!< Condition for signaling */
00269    unsigned int passthrough:1; /*!< Bit to indicate that the received packet should be passed through */
00270    unsigned int ice_port;      /*!< Port that ICE was started with if it was previously started */
00271 
00272    char remote_ufrag[256];  /*!< The remote ICE username */
00273    char remote_passwd[256]; /*!< The remote ICE password */
00274 
00275    char local_ufrag[256];  /*!< The local ICE username */
00276    char local_passwd[256]; /*!< The local ICE password */
00277 
00278    struct ao2_container *ice_local_candidates;           /*!< The local ICE candidates */
00279    struct ao2_container *ice_active_remote_candidates;   /*!< The remote ICE candidates */
00280    struct ao2_container *ice_proposed_remote_candidates; /*!< Incoming remote ICE candidates for new session */
00281    struct ast_sockaddr ice_original_rtp_addr;            /*!< rtp address that ICE started on first session */
00282 #endif
00283 
00284 #ifdef HAVE_OPENSSL_SRTP
00285    SSL_CTX *ssl_ctx; /*!< SSL context */
00286    SSL *ssl;         /*!< SSL session */
00287    BIO *read_bio;    /*!< Memory buffer for reading */
00288    BIO *write_bio;   /*!< Memory buffer for writing */
00289    enum ast_rtp_dtls_setup dtls_setup; /*!< Current setup state */
00290    enum ast_srtp_suite suite;   /*!< SRTP crypto suite */
00291    char local_fingerprint[160]; /*!< Fingerprint of our certificate */
00292    unsigned char remote_fingerprint[EVP_MAX_MD_SIZE]; /*!< Fingerprint of the peer certificate */
00293    enum ast_rtp_dtls_connection connection; /*!< Whether this is a new or existing connection */
00294    unsigned int dtls_failure:1; /*!< Failure occurred during DTLS negotiation */
00295    unsigned int rekey; /*!< Interval at which to renegotiate and rekey */
00296    int rekeyid; /*!< Scheduled item id for rekeying */
00297 #endif
00298 };
00299 
00300 /*!
00301  * \brief Structure defining an RTCP session.
00302  *
00303  * The concept "RTCP session" is not defined in RFC 3550, but since
00304  * this structure is analogous to ast_rtp, which tracks a RTP session,
00305  * it is logical to think of this as a RTCP session.
00306  *
00307  * RTCP packet is defined on page 9 of RFC 3550.
00308  *
00309  */
00310 struct ast_rtcp {
00311    int rtcp_info;
00312    int s;            /*!< Socket */
00313    struct ast_sockaddr us;    /*!< Socket representation of the local endpoint. */
00314    struct ast_sockaddr them;  /*!< Socket representation of the remote endpoint. */
00315    unsigned int soc;    /*!< What they told us */
00316    unsigned int spc;    /*!< What they told us */
00317    unsigned int themrxlsr;    /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
00318    struct timeval rxlsr;      /*!< Time when we got their last SR */
00319    struct timeval txlsr;      /*!< Time when we sent or last SR*/
00320    unsigned int expected_prior;  /*!< no. packets in previous interval */
00321    unsigned int received_prior;  /*!< no. packets received in previous interval */
00322    int schedid;         /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
00323    unsigned int rr_count;     /*!< number of RRs we've sent, not including report blocks in SR's */
00324    unsigned int sr_count;     /*!< number of SRs we've sent */
00325    unsigned int lastsrtxcount;     /*!< Transmit packet count when last SR sent */
00326    double accumulated_transit;   /*!< accumulated a-dlsr-lsr */
00327    double rtt;       /*!< Last reported rtt */
00328    unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
00329    unsigned int reported_lost;   /*!< Reported lost packets in their RR */
00330 
00331    double reported_maxjitter;
00332    double reported_minjitter;
00333    double reported_normdev_jitter;
00334    double reported_stdev_jitter;
00335    unsigned int reported_jitter_count;
00336 
00337    double reported_maxlost;
00338    double reported_minlost;
00339    double reported_normdev_lost;
00340    double reported_stdev_lost;
00341 
00342    double rxlost;
00343    double maxrxlost;
00344    double minrxlost;
00345    double normdev_rxlost;
00346    double stdev_rxlost;
00347    unsigned int rxlost_count;
00348 
00349    double maxrxjitter;
00350    double minrxjitter;
00351    double normdev_rxjitter;
00352    double stdev_rxjitter;
00353    unsigned int rxjitter_count;
00354    double maxrtt;
00355    double minrtt;
00356    double normdevrtt;
00357    double stdevrtt;
00358    unsigned int rtt_count;
00359 };
00360 
00361 struct rtp_red {
00362    struct ast_frame t140;  /*!< Primary data  */
00363    struct ast_frame t140red;   /*!< Redundant t140*/
00364    unsigned char pt[AST_RED_MAX_GENERATION];  /*!< Payload types for redundancy data */
00365    unsigned char ts[AST_RED_MAX_GENERATION]; /*!< Time stamps */
00366    unsigned char len[AST_RED_MAX_GENERATION]; /*!< length of each generation */
00367    int num_gen; /*!< Number of generations */
00368    int schedid; /*!< Timer id */
00369    int ti; /*!< How long to buffer data before send */
00370    unsigned char t140red_data[64000];
00371    unsigned char buf_data[64000]; /*!< buffered primary data */
00372    int hdrlen;
00373    long int prev_ts;
00374 };
00375 
00376 AST_LIST_HEAD_NOLOCK(frame_list, ast_frame);
00377 
00378 /* Forward Declarations */
00379 static int ast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data);
00380 static int ast_rtp_destroy(struct ast_rtp_instance *instance);
00381 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
00382 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
00383 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration);
00384 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode);
00385 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance);
00386 static void ast_rtp_update_source(struct ast_rtp_instance *instance);
00387 static void ast_rtp_change_source(struct ast_rtp_instance *instance);
00388 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
00389 static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
00390 static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
00391 static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
00392 static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
00393 static void ast_rtp_alt_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
00394 static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
00395 static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
00396 static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
00397 static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
00398 static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
00399 static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username);
00400 static void ast_rtp_stop(struct ast_rtp_instance *instance);
00401 static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char* desc);
00402 static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level);
00403 
00404 #ifdef HAVE_OPENSSL_SRTP
00405 static int ast_rtp_activate(struct ast_rtp_instance *instance);
00406 #endif
00407 
00408 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);
00409 
00410 #ifdef USE_PJPROJECT
00411 /*! \brief Destructor for locally created ICE candidates */
00412 static void ast_rtp_ice_candidate_destroy(void *obj)
00413 {
00414    struct ast_rtp_engine_ice_candidate *candidate = obj;
00415 
00416    if (candidate->foundation) {
00417       ast_free(candidate->foundation);
00418    }
00419 
00420    if (candidate->transport) {
00421       ast_free(candidate->transport);
00422    }
00423 }
00424 
00425 static void ast_rtp_ice_set_authentication(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
00426 {
00427    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00428 
00429    if (!ast_strlen_zero(ufrag)) {
00430       ast_copy_string(rtp->remote_ufrag, ufrag, sizeof(rtp->remote_ufrag));
00431    }
00432 
00433    if (!ast_strlen_zero(password)) {
00434       ast_copy_string(rtp->remote_passwd, password, sizeof(rtp->remote_passwd));
00435    }
00436 }
00437 
00438 static int ice_candidate_cmp(void *obj, void *arg, int flags)
00439 {
00440    struct ast_rtp_engine_ice_candidate *candidate1 = obj, *candidate2 = arg;
00441 
00442    if (strcmp(candidate1->foundation, candidate2->foundation) ||
00443          candidate1->id != candidate2->id ||
00444          ast_sockaddr_cmp(&candidate1->address, &candidate2->address) ||
00445          candidate1->type != candidate1->type) {
00446       return 0;
00447    }
00448 
00449    return CMP_MATCH | CMP_STOP;
00450 }
00451 
00452 static void ast_rtp_ice_add_remote_candidate(struct ast_rtp_instance *instance, const struct ast_rtp_engine_ice_candidate *candidate)
00453 {
00454    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00455    struct ast_rtp_engine_ice_candidate *remote_candidate;
00456 
00457    if (!rtp->ice_proposed_remote_candidates &&
00458          !(rtp->ice_proposed_remote_candidates = ao2_container_alloc(1, NULL, ice_candidate_cmp))) {
00459       return;
00460    }
00461 
00462    /* If this is going to exceed the maximum number of ICE candidates don't even add it */
00463    if (ao2_container_count(rtp->ice_proposed_remote_candidates) == PJ_ICE_MAX_CAND) {
00464       return;
00465    }
00466 
00467    if (!(remote_candidate = ao2_alloc(sizeof(*remote_candidate), ast_rtp_ice_candidate_destroy))) {
00468       return;
00469    }
00470 
00471    remote_candidate->foundation = ast_strdup(candidate->foundation);
00472    remote_candidate->id = candidate->id;
00473    remote_candidate->transport = ast_strdup(candidate->transport);
00474    remote_candidate->priority = candidate->priority;
00475    ast_sockaddr_copy(&remote_candidate->address, &candidate->address);
00476    ast_sockaddr_copy(&remote_candidate->relay_address, &candidate->relay_address);
00477    remote_candidate->type = candidate->type;
00478 
00479    ao2_link(rtp->ice_proposed_remote_candidates, remote_candidate);
00480    ao2_ref(remote_candidate, -1);
00481 }
00482 
00483 AST_THREADSTORAGE(pj_thread_storage);
00484 
00485 /*! \brief Function used to check if the calling thread is registered with pjlib. If it is not it will be registered. */
00486 static void pj_thread_register_check(void)
00487 {
00488    pj_thread_desc *desc;
00489    pj_thread_t *thread;
00490 
00491    if (pj_thread_is_registered() == PJ_TRUE) {
00492       return;
00493    }
00494 
00495    desc = ast_threadstorage_get(&pj_thread_storage, sizeof(pj_thread_desc));
00496    if (!desc) {
00497       ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage. Expect awful things to occur\n");
00498       return;
00499    }
00500    pj_bzero(*desc, sizeof(*desc));
00501 
00502    if (pj_thread_register("Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
00503       ast_log(LOG_ERROR, "Coudln't register thread with PJLIB.\n");
00504    }
00505    return;
00506 }
00507 
00508 /*! \brief Helper function which updates an ast_sockaddr with the candidate used for the component */
00509 static void update_address_with_ice_candidate(struct ast_rtp *rtp, int component, struct ast_sockaddr *cand_address)
00510 {
00511    char address[PJ_INET6_ADDRSTRLEN];
00512 
00513    if (!rtp->ice || (component < 1) || !rtp->ice->comp[component - 1].valid_check) {
00514       return;
00515    }
00516 
00517    ast_sockaddr_parse(cand_address, pj_sockaddr_print(&rtp->ice->comp[component - 1].valid_check->rcand->addr, address, sizeof(address), 0), 0);
00518    ast_sockaddr_set_port(cand_address, pj_sockaddr_get_port(&rtp->ice->comp[component - 1].valid_check->rcand->addr));
00519 }
00520 
00521 static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
00522    int port, int replace);
00523 
00524 static void ast_rtp_ice_stop(struct ast_rtp_instance *instance)
00525 {
00526    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00527 
00528    if (!rtp->ice) {
00529       return;
00530    }
00531 
00532    pj_thread_register_check();
00533 
00534    pj_ice_sess_destroy(rtp->ice);
00535    rtp->ice = NULL;
00536 }
00537 
00538 static int ice_reset_session(struct ast_rtp_instance *instance)
00539 {
00540    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00541 
00542    ast_rtp_ice_stop(instance);
00543    return ice_create(instance, &rtp->ice_original_rtp_addr, rtp->ice_port, 1);
00544 }
00545 
00546 static int ice_candidates_compare(struct ao2_container *left, struct ao2_container *right)
00547 {
00548    struct ao2_iterator i;
00549    struct ast_rtp_engine_ice_candidate *right_candidate;
00550 
00551    if (ao2_container_count(left) != ao2_container_count(right)) {
00552       return -1;
00553    }
00554 
00555    i = ao2_iterator_init(right, 0);
00556    while ((right_candidate = ao2_iterator_next(&i))) {
00557       struct ast_rtp_engine_ice_candidate *left_candidate = ao2_find(left, right_candidate, OBJ_POINTER);
00558 
00559       if (!left_candidate) {
00560          ao2_ref(right_candidate, -1);
00561          ao2_iterator_destroy(&i);
00562          return -1;
00563       }
00564 
00565       ao2_ref(left_candidate, -1);
00566       ao2_ref(right_candidate, -1);
00567    }
00568    ao2_iterator_destroy(&i);
00569 
00570    return 0;
00571 }
00572 
00573 static void ast_rtp_ice_start(struct ast_rtp_instance *instance)
00574 {
00575    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00576    pj_str_t ufrag = pj_str(rtp->remote_ufrag), passwd = pj_str(rtp->remote_passwd);
00577    pj_ice_sess_cand candidates[PJ_ICE_MAX_CAND];
00578    struct ao2_iterator i;
00579    struct ast_rtp_engine_ice_candidate *candidate;
00580    int cand_cnt = 0;
00581 
00582    if (!rtp->ice || !rtp->ice_proposed_remote_candidates) {
00583       return;
00584    }
00585 
00586    /* Check for equivalence in the lists */
00587    if (rtp->ice_active_remote_candidates &&
00588          !ice_candidates_compare(rtp->ice_proposed_remote_candidates, rtp->ice_active_remote_candidates)) {
00589       ao2_cleanup(rtp->ice_proposed_remote_candidates);
00590       rtp->ice_proposed_remote_candidates = NULL;
00591       return;
00592    }
00593 
00594    /* Out with the old, in with the new */
00595    ao2_cleanup(rtp->ice_active_remote_candidates);
00596    rtp->ice_active_remote_candidates = rtp->ice_proposed_remote_candidates;
00597    rtp->ice_proposed_remote_candidates = NULL;
00598 
00599    /* Reset the ICE session. Is this going to work? */
00600    if (ice_reset_session(instance)) {
00601       ast_log(LOG_NOTICE, "Failed to create replacement ICE session\n");
00602       return;
00603    }
00604 
00605    pj_thread_register_check();
00606 
00607    i = ao2_iterator_init(rtp->ice_active_remote_candidates, 0);
00608 
00609    while ((candidate = ao2_iterator_next(&i)) && (cand_cnt < PJ_ICE_MAX_CAND)) {
00610       pj_str_t address;
00611 
00612       pj_strdup2(rtp->ice->pool, &candidates[cand_cnt].foundation, candidate->foundation);
00613       candidates[cand_cnt].comp_id = candidate->id;
00614       candidates[cand_cnt].prio = candidate->priority;
00615 
00616       pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->address)), &candidates[cand_cnt].addr);
00617 
00618       if (!ast_sockaddr_isnull(&candidate->relay_address)) {
00619          pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->relay_address)), &candidates[cand_cnt].rel_addr);
00620       }
00621 
00622       if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
00623          candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_HOST;
00624       } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
00625          candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_SRFLX;
00626       } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
00627          candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_RELAYED;
00628       }
00629 
00630       if (candidate->id == AST_RTP_ICE_COMPONENT_RTP && rtp->turn_rtp) {
00631          pj_turn_sock_set_perm(rtp->turn_rtp, 1, &candidates[cand_cnt].addr, 1);
00632       } else if (candidate->id == AST_RTP_ICE_COMPONENT_RTCP && rtp->turn_rtcp) {
00633          pj_turn_sock_set_perm(rtp->turn_rtcp, 1, &candidates[cand_cnt].addr, 1);
00634       }
00635 
00636       cand_cnt++;
00637       ao2_ref(candidate, -1);
00638    }
00639 
00640    ao2_iterator_destroy(&i);
00641 
00642    if (pj_ice_sess_create_check_list(rtp->ice, &ufrag, &passwd, ao2_container_count(rtp->ice_active_remote_candidates), &candidates[0]) == PJ_SUCCESS) {
00643       ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: SUCCESS");
00644       pj_ice_sess_start_check(rtp->ice);
00645       pj_timer_heap_poll(timerheap, NULL);
00646       rtp->strict_rtp_state = STRICT_RTP_OPEN;
00647       return;
00648    }
00649 
00650    ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: FAILURE");
00651 
00652    /* even though create check list failed don't stop ice as
00653       it might still work */
00654    ast_debug(1, "Failed to create ICE session check list\n");
00655    /* however we do need to reset remote candidates since
00656       this function may be re-entered */
00657    ao2_ref(rtp->ice_active_remote_candidates, -1);
00658    rtp->ice_active_remote_candidates = NULL;
00659    rtp->ice->rcand_cnt = rtp->ice->clist.count = 0;
00660 }
00661 
00662 static const char *ast_rtp_ice_get_ufrag(struct ast_rtp_instance *instance)
00663 {
00664    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00665 
00666    return rtp->local_ufrag;
00667 }
00668 
00669 static const char *ast_rtp_ice_get_password(struct ast_rtp_instance *instance)
00670 {
00671    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00672 
00673    return rtp->local_passwd;
00674 }
00675 
00676 static struct ao2_container *ast_rtp_ice_get_local_candidates(struct ast_rtp_instance *instance)
00677 {
00678    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00679 
00680    if (rtp->ice_local_candidates) {
00681       ao2_ref(rtp->ice_local_candidates, +1);
00682    }
00683 
00684    return rtp->ice_local_candidates;
00685 }
00686 
00687 static void ast_rtp_ice_lite(struct ast_rtp_instance *instance)
00688 {
00689    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00690 
00691    if (!rtp->ice) {
00692       return;
00693    }
00694 
00695    pj_thread_register_check();
00696 
00697    pj_ice_sess_change_role(rtp->ice, PJ_ICE_SESS_ROLE_CONTROLLING);
00698 }
00699 
00700 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,
00701                const pj_sockaddr_t *addr, const pj_sockaddr_t *base_addr, const pj_sockaddr_t *rel_addr, int addr_len)
00702 {
00703    pj_str_t foundation;
00704    struct ast_rtp_engine_ice_candidate *candidate, *existing;
00705    char address[PJ_INET6_ADDRSTRLEN];
00706 
00707    pj_thread_register_check();
00708 
00709    pj_ice_calc_foundation(rtp->ice->pool, &foundation, type, addr);
00710 
00711    if (!rtp->ice_local_candidates && !(rtp->ice_local_candidates = ao2_container_alloc(1, NULL, ice_candidate_cmp))) {
00712       return;
00713    }
00714 
00715    if (!(candidate = ao2_alloc(sizeof(*candidate), ast_rtp_ice_candidate_destroy))) {
00716       return;
00717    }
00718 
00719    candidate->foundation = ast_strndup(pj_strbuf(&foundation), pj_strlen(&foundation));
00720    candidate->id = comp_id;
00721    candidate->transport = ast_strdup("UDP");
00722 
00723    ast_sockaddr_parse(&candidate->address, pj_sockaddr_print(addr, address, sizeof(address), 0), 0);
00724    ast_sockaddr_set_port(&candidate->address, pj_sockaddr_get_port(addr));
00725 
00726    if (rel_addr) {
00727       ast_sockaddr_parse(&candidate->relay_address, pj_sockaddr_print(rel_addr, address, sizeof(address), 0), 0);
00728       ast_sockaddr_set_port(&candidate->relay_address, pj_sockaddr_get_port(rel_addr));
00729    }
00730 
00731    if (type == PJ_ICE_CAND_TYPE_HOST) {
00732       candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
00733    } else if (type == PJ_ICE_CAND_TYPE_SRFLX) {
00734       candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
00735    } else if (type == PJ_ICE_CAND_TYPE_RELAYED) {
00736       candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
00737    }
00738 
00739    if ((existing = ao2_find(rtp->ice_local_candidates, candidate, OBJ_POINTER))) {
00740       ao2_ref(existing, -1);
00741       ao2_ref(candidate, -1);
00742       return;
00743    }
00744 
00745    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) {
00746       ao2_ref(candidate, -1);
00747       return;
00748    }
00749 
00750    /* By placing the candidate into the ICE session it will have produced the priority, so update the local candidate with it */
00751    candidate->priority = rtp->ice->lcand[rtp->ice->lcand_cnt - 1].prio;
00752 
00753    ao2_link(rtp->ice_local_candidates, candidate);
00754    ao2_ref(candidate, -1);
00755 }
00756 
00757 static char *generate_random_string(char *buf, size_t size)
00758 {
00759         long val[4];
00760         int x;
00761 
00762         for (x=0; x<4; x++)
00763                 val[x] = ast_random();
00764         snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
00765 
00766         return buf;
00767 }
00768 
00769 /* ICE RTP Engine interface declaration */
00770 static struct ast_rtp_engine_ice ast_rtp_ice = {
00771    .set_authentication = ast_rtp_ice_set_authentication,
00772    .add_remote_candidate = ast_rtp_ice_add_remote_candidate,
00773    .start = ast_rtp_ice_start,
00774    .stop = ast_rtp_ice_stop,
00775    .get_ufrag = ast_rtp_ice_get_ufrag,
00776    .get_password = ast_rtp_ice_get_password,
00777    .get_local_candidates = ast_rtp_ice_get_local_candidates,
00778    .ice_lite = ast_rtp_ice_lite,
00779 };
00780 #endif
00781 
00782 #ifdef HAVE_OPENSSL_SRTP
00783 static void dtls_info_callback(const SSL *ssl, int where, int ret)
00784 {
00785    struct ast_rtp *rtp = SSL_get_ex_data(ssl, 0);
00786 
00787    /* We only care about alerts */
00788    if (!(where & SSL_CB_ALERT)) {
00789       return;
00790    }
00791 
00792    rtp->dtls_failure = 1;
00793 }
00794 
00795 static int ast_rtp_dtls_set_configuration(struct ast_rtp_instance *instance, const struct ast_rtp_dtls_cfg *dtls_cfg)
00796 {
00797    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00798 
00799    if (!dtls_cfg->enabled) {
00800       return 0;
00801    }
00802 
00803    if (!ast_rtp_engine_srtp_is_registered()) {
00804       return -1;
00805    }
00806 
00807    if (!(rtp->ssl_ctx = SSL_CTX_new(DTLSv1_method()))) {
00808       return -1;
00809    }
00810 
00811    SSL_CTX_set_verify(rtp->ssl_ctx, dtls_cfg->verify ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE, NULL);
00812 
00813    if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_80) {
00814       SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_80");
00815    } else if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_32) {
00816       SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_32");
00817    } else {
00818       ast_log(LOG_ERROR, "Unsupported suite specified for DTLS-SRTP on RTP instance '%p'\n", instance);
00819       goto error;
00820    }
00821 
00822    if (!ast_strlen_zero(dtls_cfg->certfile)) {
00823       char *private = ast_strlen_zero(dtls_cfg->pvtfile) ? dtls_cfg->certfile : dtls_cfg->pvtfile;
00824       BIO *certbio;
00825       X509 *cert;
00826       unsigned int size, i;
00827       unsigned char fingerprint[EVP_MAX_MD_SIZE];
00828       char *local_fingerprint = rtp->local_fingerprint;
00829 
00830       if (!SSL_CTX_use_certificate_file(rtp->ssl_ctx, dtls_cfg->certfile, SSL_FILETYPE_PEM)) {
00831          ast_log(LOG_ERROR, "Specified certificate file '%s' for RTP instance '%p' could not be used\n",
00832             dtls_cfg->certfile, instance);
00833          goto error;
00834       }
00835 
00836       if (!SSL_CTX_use_PrivateKey_file(rtp->ssl_ctx, private, SSL_FILETYPE_PEM) ||
00837           !SSL_CTX_check_private_key(rtp->ssl_ctx)) {
00838          ast_log(LOG_ERROR, "Specified private key file '%s' for RTP instance '%p' could not be used\n",
00839             private, instance);
00840          goto error;
00841       }
00842 
00843       if (!(certbio = BIO_new(BIO_s_file()))) {
00844          ast_log(LOG_ERROR, "Failed to allocate memory for certificate fingerprinting on RTP instance '%p'\n",
00845             instance);
00846          goto error;
00847       }
00848 
00849       if (!BIO_read_filename(certbio, dtls_cfg->certfile) ||
00850           !(cert = PEM_read_bio_X509(certbio, NULL, 0, NULL)) ||
00851           !X509_digest(cert, EVP_sha1(), fingerprint, &size) ||
00852           !size) {
00853          ast_log(LOG_ERROR, "Could not produce fingerprint from certificate '%s' for RTP instance '%p'\n",
00854             dtls_cfg->certfile, instance);
00855          BIO_free_all(certbio);
00856          goto error;
00857       }
00858 
00859       for (i = 0; i < size; i++) {
00860          sprintf(local_fingerprint, "%.2X:", fingerprint[i]);
00861          local_fingerprint += 3;
00862       }
00863 
00864       *(local_fingerprint-1) = 0;
00865 
00866       BIO_free_all(certbio);
00867    }
00868 
00869    if (!ast_strlen_zero(dtls_cfg->cipher)) {
00870       if (!SSL_CTX_set_cipher_list(rtp->ssl_ctx, dtls_cfg->cipher)) {
00871          ast_log(LOG_ERROR, "Invalid cipher specified in cipher list '%s' for RTP instance '%p'\n",
00872             dtls_cfg->cipher, instance);
00873          goto error;
00874       }
00875    }
00876 
00877    if (!ast_strlen_zero(dtls_cfg->cafile) || !ast_strlen_zero(dtls_cfg->capath)) {
00878       if (!SSL_CTX_load_verify_locations(rtp->ssl_ctx, S_OR(dtls_cfg->cafile, NULL), S_OR(dtls_cfg->capath, NULL))) {
00879          ast_log(LOG_ERROR, "Invalid certificate authority file '%s' or path '%s' specified for RTP instance '%p'\n",
00880             S_OR(dtls_cfg->cafile, ""), S_OR(dtls_cfg->capath, ""), instance);
00881          goto error;
00882       }
00883    }
00884 
00885    rtp->rekey = dtls_cfg->rekey;
00886    rtp->dtls_setup = dtls_cfg->default_setup;
00887    rtp->suite = dtls_cfg->suite;
00888 
00889    if (!(rtp->ssl = SSL_new(rtp->ssl_ctx))) {
00890       ast_log(LOG_ERROR, "Failed to allocate memory for SSL context on RTP instance '%p'\n",
00891          instance);
00892       goto error;
00893    }
00894 
00895    SSL_set_ex_data(rtp->ssl, 0, rtp);
00896    SSL_set_info_callback(rtp->ssl, dtls_info_callback);
00897 
00898    if (!(rtp->read_bio = BIO_new(BIO_s_mem()))) {
00899       ast_log(LOG_ERROR, "Failed to allocate memory for inbound SSL traffic on RTP instance '%p'\n",
00900          instance);
00901       goto error;
00902    }
00903    BIO_set_mem_eof_return(rtp->read_bio, -1);
00904 
00905    if (!(rtp->write_bio = BIO_new(BIO_s_mem()))) {
00906       ast_log(LOG_ERROR, "Failed to allocate memory for outbound SSL traffic on RTP instance '%p'\n",
00907          instance);
00908       goto error;
00909    }
00910    BIO_set_mem_eof_return(rtp->write_bio, -1);
00911 
00912    SSL_set_bio(rtp->ssl, rtp->read_bio, rtp->write_bio);
00913 
00914    if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
00915       SSL_set_accept_state(rtp->ssl);
00916    } else {
00917       SSL_set_connect_state(rtp->ssl);
00918    }
00919 
00920    rtp->connection = AST_RTP_DTLS_CONNECTION_NEW;
00921 
00922    return 0;
00923 
00924 error:
00925    if (rtp->read_bio) {
00926       BIO_free(rtp->read_bio);
00927       rtp->read_bio = NULL;
00928    }
00929 
00930    if (rtp->write_bio) {
00931       BIO_free(rtp->write_bio);
00932       rtp->write_bio = NULL;
00933    }
00934 
00935    if (rtp->ssl) {
00936       SSL_free(rtp->ssl);
00937       rtp->ssl = NULL;
00938    }
00939 
00940    SSL_CTX_free(rtp->ssl_ctx);
00941    rtp->ssl_ctx = NULL;
00942 
00943    return -1;
00944 }
00945 
00946 static int ast_rtp_dtls_active(struct ast_rtp_instance *instance)
00947 {
00948    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00949 
00950    return !rtp->ssl_ctx ? 0 : 1;
00951 }
00952 
00953 static void ast_rtp_dtls_stop(struct ast_rtp_instance *instance)
00954 {
00955    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00956 
00957    if (rtp->ssl_ctx) {
00958       SSL_CTX_free(rtp->ssl_ctx);
00959       rtp->ssl_ctx = NULL;
00960    }
00961 
00962    if (rtp->ssl) {
00963       SSL_free(rtp->ssl);
00964       rtp->ssl = NULL;
00965    }
00966 }
00967 
00968 static void ast_rtp_dtls_reset(struct ast_rtp_instance *instance)
00969 {
00970    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00971 
00972    /* If the SSL session is not yet finalized don't bother resetting */
00973    if (!SSL_is_init_finished(rtp->ssl)) {
00974       return;
00975    }
00976 
00977    SSL_shutdown(rtp->ssl);
00978    rtp->connection = AST_RTP_DTLS_CONNECTION_NEW;
00979 }
00980 
00981 static enum ast_rtp_dtls_connection ast_rtp_dtls_get_connection(struct ast_rtp_instance *instance)
00982 {
00983    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00984 
00985    return rtp->connection;
00986 }
00987 
00988 static enum ast_rtp_dtls_setup ast_rtp_dtls_get_setup(struct ast_rtp_instance *instance)
00989 {
00990    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00991 
00992    return rtp->dtls_setup;
00993 }
00994 
00995 static void ast_rtp_dtls_set_setup(struct ast_rtp_instance *instance, enum ast_rtp_dtls_setup setup)
00996 {
00997    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00998    enum ast_rtp_dtls_setup old = rtp->dtls_setup;
00999 
01000    switch (setup) {
01001    case AST_RTP_DTLS_SETUP_ACTIVE:
01002       rtp->dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
01003       break;
01004    case AST_RTP_DTLS_SETUP_PASSIVE:
01005       rtp->dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
01006       break;
01007    case AST_RTP_DTLS_SETUP_ACTPASS:
01008       /* We can't respond to an actpass setup with actpass ourselves... so respond with active, as we can initiate connections */
01009       if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
01010          rtp->dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
01011       }
01012       break;
01013    case AST_RTP_DTLS_SETUP_HOLDCONN:
01014       rtp->dtls_setup = AST_RTP_DTLS_SETUP_HOLDCONN;
01015       break;
01016    default:
01017       /* This should never occur... if it does exit early as we don't know what state things are in */
01018       return;
01019    }
01020 
01021    /* If the setup state did not change we go on as if nothing happened */
01022    if (old == rtp->dtls_setup) {
01023       return;
01024    }
01025 
01026    /* If they don't want us to establish a connection wait until later */
01027    if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_HOLDCONN) {
01028       return;
01029    }
01030 
01031    if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
01032       SSL_set_connect_state(rtp->ssl);
01033    } else if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
01034       SSL_set_accept_state(rtp->ssl);
01035    } else {
01036       return;
01037    }
01038 }
01039 
01040 static void ast_rtp_dtls_set_fingerprint(struct ast_rtp_instance *instance, enum ast_rtp_dtls_hash hash, const char *fingerprint)
01041 {
01042    char *tmp = ast_strdupa(fingerprint), *value;
01043    int pos = 0;
01044    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01045 
01046    if (hash != AST_RTP_DTLS_HASH_SHA1) {
01047       return;
01048    }
01049 
01050    while ((value = strsep(&tmp, ":")) && (pos != (EVP_MAX_MD_SIZE - 1))) {
01051       sscanf(value, "%02x", (unsigned int*)&rtp->remote_fingerprint[pos++]);
01052    }
01053 }
01054 
01055 static const char *ast_rtp_dtls_get_fingerprint(struct ast_rtp_instance *instance, enum ast_rtp_dtls_hash hash)
01056 {
01057    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01058 
01059    if (hash != AST_RTP_DTLS_HASH_SHA1) {
01060       return NULL;
01061    }
01062 
01063    return rtp->local_fingerprint;
01064 }
01065 
01066 /* DTLS RTP Engine interface declaration */
01067 static struct ast_rtp_engine_dtls ast_rtp_dtls = {
01068    .set_configuration = ast_rtp_dtls_set_configuration,
01069    .active = ast_rtp_dtls_active,
01070    .stop = ast_rtp_dtls_stop,
01071    .reset = ast_rtp_dtls_reset,
01072    .get_connection = ast_rtp_dtls_get_connection,
01073    .get_setup = ast_rtp_dtls_get_setup,
01074    .set_setup = ast_rtp_dtls_set_setup,
01075    .set_fingerprint = ast_rtp_dtls_set_fingerprint,
01076    .get_fingerprint = ast_rtp_dtls_get_fingerprint,
01077 };
01078 
01079 #endif
01080 
01081 /* RTP Engine Declaration */
01082 static struct ast_rtp_engine asterisk_rtp_engine = {
01083    .name = "asterisk",
01084    .new = ast_rtp_new,
01085    .destroy = ast_rtp_destroy,
01086    .dtmf_begin = ast_rtp_dtmf_begin,
01087    .dtmf_end = ast_rtp_dtmf_end,
01088    .dtmf_end_with_duration = ast_rtp_dtmf_end_with_duration,
01089    .dtmf_mode_set = ast_rtp_dtmf_mode_set,
01090    .dtmf_mode_get = ast_rtp_dtmf_mode_get,
01091    .update_source = ast_rtp_update_source,
01092    .change_source = ast_rtp_change_source,
01093    .write = ast_rtp_write,
01094    .read = ast_rtp_read,
01095    .prop_set = ast_rtp_prop_set,
01096    .fd = ast_rtp_fd,
01097    .remote_address_set = ast_rtp_remote_address_set,
01098    .alt_remote_address_set = ast_rtp_alt_remote_address_set,
01099    .red_init = rtp_red_init,
01100    .red_buffer = rtp_red_buffer,
01101    .local_bridge = ast_rtp_local_bridge,
01102    .get_stat = ast_rtp_get_stat,
01103    .dtmf_compatible = ast_rtp_dtmf_compatible,
01104    .stun_request = ast_rtp_stun_request,
01105    .stop = ast_rtp_stop,
01106    .qos = ast_rtp_qos_set,
01107    .sendcng = ast_rtp_sendcng,
01108 #ifdef USE_PJPROJECT
01109    .ice = &ast_rtp_ice,
01110 #endif
01111 #ifdef HAVE_OPENSSL_SRTP
01112    .dtls = &ast_rtp_dtls,
01113    .activate = ast_rtp_activate,
01114 #endif
01115 };
01116 
01117 static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq);
01118 
01119 #ifdef USE_PJPROJECT
01120 static void ast_rtp_on_ice_complete(pj_ice_sess *ice, pj_status_t status)
01121 {
01122    struct ast_rtp *rtp = ice->user_data;
01123 
01124    if (!strictrtp) {
01125       return;
01126    }
01127 
01128    rtp->strict_rtp_state = STRICT_RTP_LEARN;
01129    rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t)rtp->seqno);
01130 }
01131 
01132 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)
01133 {
01134    struct ast_rtp *rtp = ice->user_data;
01135 
01136    /* 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
01137     * returns */
01138    rtp->passthrough = 1;
01139 }
01140 
01141 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)
01142 {
01143    struct ast_rtp *rtp = ice->user_data;
01144    pj_status_t status = PJ_EINVALIDOP;
01145    pj_ssize_t _size = (pj_ssize_t)size;
01146 
01147    if (transport_id == TRANSPORT_SOCKET_RTP) {
01148       /* Traffic is destined to go right out the RTP socket we already have */
01149       status = pj_sock_sendto(rtp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
01150       /* sendto on a connectionless socket should send all the data, or none at all */
01151       ast_assert(_size == size || status != PJ_SUCCESS);
01152    } else if (transport_id == TRANSPORT_SOCKET_RTCP) {
01153       /* Traffic is destined to go right out the RTCP socket we already have */
01154       if (rtp->rtcp) {
01155          status = pj_sock_sendto(rtp->rtcp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
01156          /* sendto on a connectionless socket should send all the data, or none at all */
01157          ast_assert(_size == size || status != PJ_SUCCESS);
01158       } else {
01159          status = PJ_SUCCESS;
01160       }
01161    } else if (transport_id == TRANSPORT_TURN_RTP) {
01162       /* Traffic is going through the RTP TURN relay */
01163       if (rtp->turn_rtp) {
01164          status = pj_turn_sock_sendto(rtp->turn_rtp, pkt, size, dst_addr, dst_addr_len);
01165       }
01166    } else if (transport_id == TRANSPORT_TURN_RTCP) {
01167       /* Traffic is going through the RTCP TURN relay */
01168       if (rtp->turn_rtcp) {
01169          status = pj_turn_sock_sendto(rtp->turn_rtcp, pkt, size, dst_addr, dst_addr_len);
01170       }
01171    }
01172 
01173    return status;
01174 }
01175 
01176 /* ICE Session interface declaration */
01177 static pj_ice_sess_cb ast_rtp_ice_sess_cb = {
01178    .on_ice_complete = ast_rtp_on_ice_complete,
01179    .on_rx_data = ast_rtp_on_ice_rx_data,
01180    .on_tx_pkt = ast_rtp_on_ice_tx_pkt,
01181 };
01182 
01183 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)
01184 {
01185    struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
01186    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01187    struct ast_sockaddr dest = { { 0, }, };
01188 
01189    ast_rtp_instance_get_local_address(instance, &dest);
01190 
01191    ast_sendto(rtp->s, pkt, pkt_len, 0, &dest);
01192 }
01193 
01194 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)
01195 {
01196    struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
01197    struct ast_rtp *rtp = NULL;
01198 
01199    /* If this is a leftover from an already destroyed RTP instance just ignore the state change */
01200    if (!instance) {
01201       return;
01202    }
01203 
01204    rtp = ast_rtp_instance_get_data(instance);
01205 
01206    /* If the TURN session is being destroyed we need to remove it from the RTP instance */
01207    if (new_state == PJ_TURN_STATE_DESTROYING) {
01208       rtp->turn_rtp = NULL;
01209       return;
01210    }
01211 
01212    /* We store the new state so the other thread can actually handle it */
01213    ast_mutex_lock(&rtp->lock);
01214    rtp->turn_state = new_state;
01215 
01216    /* If this is a state that the main thread should be notified about do so */
01217    if (new_state == PJ_TURN_STATE_READY || new_state == PJ_TURN_STATE_DEALLOCATING || new_state == PJ_TURN_STATE_DEALLOCATED) {
01218       ast_cond_signal(&rtp->cond);
01219    }
01220 
01221    ast_mutex_unlock(&rtp->lock);
01222 }
01223 
01224 /* RTP TURN Socket interface declaration */
01225 static pj_turn_sock_cb ast_rtp_turn_rtp_sock_cb = {
01226    .on_rx_data = ast_rtp_on_turn_rx_rtp_data,
01227    .on_state = ast_rtp_on_turn_rtp_state,
01228 };
01229 
01230 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)
01231 {
01232    struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
01233    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01234 
01235    ast_sendto(rtp->rtcp->s, pkt, pkt_len, 0, &rtp->rtcp->us);
01236 }
01237 
01238 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)
01239 {
01240    struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
01241    struct ast_rtp *rtp = NULL;
01242 
01243    /* If this is a leftover from an already destroyed RTP instance just ignore the state change */
01244    if (!instance) {
01245       return;
01246    }
01247 
01248    rtp = ast_rtp_instance_get_data(instance);
01249 
01250    /* If the TURN session is being destroyed we need to remove it from the RTP instance */
01251    if (new_state == PJ_TURN_STATE_DESTROYING) {
01252       rtp->turn_rtcp = NULL;
01253       return;
01254    }
01255 
01256    /* We store the new state so the other thread can actually handle it */
01257    ast_mutex_lock(&rtp->lock);
01258    rtp->turn_state = new_state;
01259 
01260    /* If this is a state that the main thread should be notified about do so */
01261    if (new_state == PJ_TURN_STATE_READY || new_state == PJ_TURN_STATE_DEALLOCATING || new_state == PJ_TURN_STATE_DEALLOCATED) {
01262       ast_cond_signal(&rtp->cond);
01263    }
01264 
01265        ast_mutex_unlock(&rtp->lock);
01266 }
01267 
01268 /* RTCP TURN Socket interface declaration */
01269 static pj_turn_sock_cb ast_rtp_turn_rtcp_sock_cb = {
01270    .on_rx_data = ast_rtp_on_turn_rx_rtcp_data,
01271    .on_state = ast_rtp_on_turn_rtcp_state,
01272 };
01273 
01274 /*! \brief Worker thread for I/O queue and timerheap */
01275 static int ice_worker_thread(void *data)
01276 {
01277    while (!worker_terminate) {
01278       const pj_time_val delay = {0, 10};
01279 
01280       pj_ioqueue_poll(ioqueue, &delay);
01281 
01282       pj_timer_heap_poll(timerheap, NULL);
01283    }
01284 
01285    return 0;
01286 }
01287 #endif
01288 
01289 static inline int rtp_debug_test_addr(struct ast_sockaddr *addr)
01290 {
01291    if (!rtpdebug) {
01292       return 0;
01293    }
01294    if (!ast_sockaddr_isnull(&rtpdebugaddr)) {
01295       if (rtpdebugport) {
01296          return (ast_sockaddr_cmp(&rtpdebugaddr, addr) == 0); /* look for RTP packets from IP+Port */
01297       } else {
01298          return (ast_sockaddr_cmp_addr(&rtpdebugaddr, addr) == 0); /* only look for RTP packets from IP */
01299       }
01300    }
01301 
01302    return 1;
01303 }
01304 
01305 static inline int rtcp_debug_test_addr(struct ast_sockaddr *addr)
01306 {
01307    if (!rtcpdebug) {
01308       return 0;
01309    }
01310    if (!ast_sockaddr_isnull(&rtcpdebugaddr)) {
01311       if (rtcpdebugport) {
01312          return (ast_sockaddr_cmp(&rtcpdebugaddr, addr) == 0); /* look for RTCP packets from IP+Port */
01313       } else {
01314          return (ast_sockaddr_cmp_addr(&rtcpdebugaddr, addr) == 0); /* only look for RTCP packets from IP */
01315       }
01316    }
01317 
01318    return 1;
01319 }
01320 
01321 #ifdef HAVE_OPENSSL_SRTP
01322 static void dtls_srtp_check_pending(struct ast_rtp_instance *instance, struct ast_rtp *rtp)
01323 {
01324    size_t pending = BIO_ctrl_pending(rtp->write_bio);
01325 
01326    if (pending > 0) {
01327       char outgoing[pending];
01328       size_t out;
01329       struct ast_sockaddr remote_address = { {0, } };
01330       int ice;
01331 
01332       ast_rtp_instance_get_remote_address(instance, &remote_address);
01333 
01334       /* If we do not yet know an address to send this to defer it until we do */
01335       if (ast_sockaddr_isnull(&remote_address)) {
01336          return;
01337       }
01338 
01339       out = BIO_read(rtp->write_bio, outgoing, sizeof(outgoing));
01340 
01341       __rtp_sendto(instance, outgoing, out, 0, &remote_address, 0, &ice, 0);
01342    }
01343 }
01344 
01345 static int dtls_srtp_renegotiate(const void *data)
01346 {
01347    struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
01348    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01349 
01350    SSL_renegotiate(rtp->ssl);
01351    SSL_do_handshake(rtp->ssl);
01352    dtls_srtp_check_pending(instance, rtp);
01353 
01354    rtp->rekeyid = -1;
01355    ao2_ref(instance, -1);
01356 
01357    return 0;
01358 }
01359 
01360 static int dtls_srtp_setup(struct ast_rtp *rtp, struct ast_srtp *srtp, struct ast_rtp_instance *instance)
01361 {
01362    unsigned char material[SRTP_MASTER_LEN * 2];
01363    unsigned char *local_key, *local_salt, *remote_key, *remote_salt;
01364    struct ast_srtp_policy *local_policy, *remote_policy = NULL;
01365    struct ast_rtp_instance_stats stats = { 0, };
01366 
01367    /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
01368    if (SSL_CTX_get_verify_mode(rtp->ssl_ctx) != SSL_VERIFY_NONE) {
01369       X509 *certificate;
01370 
01371       if (!(certificate = SSL_get_peer_certificate(rtp->ssl))) {
01372          ast_log(LOG_WARNING, "No certificate was provided by the peer on RTP instance '%p'\n", instance);
01373          return -1;
01374       }
01375 
01376       /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
01377       if (rtp->remote_fingerprint[0]) {
01378          unsigned char fingerprint[EVP_MAX_MD_SIZE];
01379          unsigned int size;
01380 
01381          if (!X509_digest(certificate, EVP_sha1(), fingerprint, &size) ||
01382              !size ||
01383              memcmp(fingerprint, rtp->remote_fingerprint, size)) {
01384             X509_free(certificate);
01385             ast_log(LOG_WARNING, "Fingerprint provided by remote party does not match that of peer certificate on RTP instance '%p'\n",
01386                instance);
01387             return -1;
01388          }
01389       }
01390 
01391       X509_free(certificate);
01392    }
01393 
01394    /* Ensure that certificate verification was successful */
01395    if (SSL_get_verify_result(rtp->ssl) != X509_V_OK) {
01396       ast_log(LOG_WARNING, "Peer certificate on RTP instance '%p' failed verification test\n",
01397          instance);
01398       return -1;
01399    }
01400 
01401    /* Produce key information and set up SRTP */
01402    if (!SSL_export_keying_material(rtp->ssl, material, SRTP_MASTER_LEN * 2, "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
01403       ast_log(LOG_WARNING, "Unable to extract SRTP keying material from DTLS-SRTP negotiation on RTP instance '%p'\n",
01404          instance);
01405       return -1;
01406    }
01407 
01408    /* Whether we are acting as a server or client determines where the keys/salts are */
01409    if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
01410       local_key = material;
01411       remote_key = local_key + SRTP_MASTER_KEY_LEN;
01412       local_salt = remote_key + SRTP_MASTER_KEY_LEN;
01413       remote_salt = local_salt + SRTP_MASTER_SALT_LEN;
01414    } else {
01415       remote_key = material;
01416       local_key = remote_key + SRTP_MASTER_KEY_LEN;
01417       remote_salt = local_key + SRTP_MASTER_KEY_LEN;
01418       local_salt = remote_salt + SRTP_MASTER_SALT_LEN;
01419    }
01420 
01421    if (!(local_policy = res_srtp_policy->alloc())) {
01422       return -1;
01423    }
01424 
01425    if (res_srtp_policy->set_master_key(local_policy, local_key, SRTP_MASTER_KEY_LEN, local_salt, SRTP_MASTER_SALT_LEN) < 0) {
01426       ast_log(LOG_WARNING, "Could not set key/salt information on local policy of '%p' when setting up DTLS-SRTP\n", rtp);
01427       goto error;
01428    }
01429 
01430    if (res_srtp_policy->set_suite(local_policy, rtp->suite)) {
01431       ast_log(LOG_WARNING, "Could not set suite to '%d' on local policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
01432       goto error;
01433    }
01434 
01435    if (ast_rtp_instance_get_stats(instance, &stats, AST_RTP_INSTANCE_STAT_LOCAL_SSRC)) {
01436       goto error;
01437    }
01438 
01439    res_srtp_policy->set_ssrc(local_policy, stats.local_ssrc, 0);
01440 
01441    if (!(remote_policy = res_srtp_policy->alloc())) {
01442       goto error;
01443    }
01444 
01445    if (res_srtp_policy->set_master_key(remote_policy, remote_key, SRTP_MASTER_KEY_LEN, remote_salt, SRTP_MASTER_SALT_LEN) < 0) {
01446       ast_log(LOG_WARNING, "Could not set key/salt information on remote policy of '%p' when setting up DTLS-SRTP\n", rtp);
01447       goto error;
01448    }
01449 
01450    if (res_srtp_policy->set_suite(remote_policy, rtp->suite)) {
01451       ast_log(LOG_WARNING, "Could not set suite to '%d' on remote policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
01452       goto error;
01453    }
01454 
01455    res_srtp_policy->set_ssrc(remote_policy, 0, 1);
01456 
01457    if (ast_rtp_instance_add_srtp_policy(instance, remote_policy, local_policy)) {
01458       ast_log(LOG_WARNING, "Could not set policies when setting up DTLS-SRTP on '%p'\n", rtp);
01459       goto error;
01460    }
01461 
01462    if (rtp->rekey) {
01463       ao2_ref(instance, +1);
01464       if ((rtp->rekeyid = ast_sched_add(rtp->sched, rtp->rekey * 1000, dtls_srtp_renegotiate, instance)) < 0) {
01465          ao2_ref(instance, -1);
01466          goto error;
01467       }
01468    }
01469 
01470    return 0;
01471 
01472 error:
01473    res_srtp_policy->destroy(local_policy);
01474 
01475    if (remote_policy) {
01476       res_srtp_policy->destroy(remote_policy);
01477    }
01478 
01479    return -1;
01480 }
01481 #endif
01482 
01483 static int __rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
01484 {
01485    int len;
01486    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01487    struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
01488    char *in = buf;
01489 
01490    if ((len = ast_recvfrom(rtcp ? rtp->rtcp->s : rtp->s, buf, size, flags, sa)) < 0) {
01491       return len;
01492    }
01493 
01494 #ifdef HAVE_OPENSSL_SRTP
01495    if (!rtcp) {
01496       dtls_srtp_check_pending(instance, rtp);
01497 
01498       /* If this is an SSL packet pass it to OpenSSL for processing */
01499       if ((*in >= 20) && (*in <= 64)) {
01500          int res = 0;
01501 
01502          /* If no SSL session actually exists terminate things */
01503          if (!rtp->ssl) {
01504             ast_log(LOG_ERROR, "Received SSL traffic on RTP instance '%p' without an SSL session\n",
01505                instance);
01506             return -1;
01507          }
01508 
01509          /* If we don't yet know if we are active or passive and we receive a packet... we are obviously passive */
01510          if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
01511             rtp->dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
01512             SSL_set_accept_state(rtp->ssl);
01513          }
01514 
01515          dtls_srtp_check_pending(instance, rtp);
01516 
01517          BIO_write(rtp->read_bio, buf, len);
01518 
01519          len = SSL_read(rtp->ssl, buf, len);
01520 
01521          dtls_srtp_check_pending(instance, rtp);
01522 
01523          if (rtp->dtls_failure) {
01524             ast_log(LOG_ERROR, "DTLS failure occurred on RTP instance '%p', terminating\n",
01525                instance);
01526             return -1;
01527          }
01528 
01529          if (SSL_is_init_finished(rtp->ssl)) {
01530             /* Any further connections will be existing since this is now established */
01531             rtp->connection = AST_RTP_DTLS_CONNECTION_EXISTING;
01532 
01533             /* Use the keying material to set up key/salt information */
01534             res = dtls_srtp_setup(rtp, srtp, instance);
01535          }
01536 
01537          return res;
01538       }
01539    }
01540 #endif
01541 
01542 #ifdef USE_PJPROJECT
01543    if (rtp->ice) {
01544       pj_str_t combined = pj_str(ast_sockaddr_stringify(sa));
01545       pj_sockaddr address;
01546       pj_status_t status;
01547 
01548       pj_thread_register_check();
01549 
01550       pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &combined, &address);
01551 
01552       status = pj_ice_sess_on_rx_pkt(rtp->ice, rtcp ? AST_RTP_ICE_COMPONENT_RTCP : AST_RTP_ICE_COMPONENT_RTP,
01553          rtcp ? TRANSPORT_SOCKET_RTCP : TRANSPORT_SOCKET_RTP, buf, len, &address,
01554          pj_sockaddr_get_len(&address));
01555       if (status != PJ_SUCCESS) {
01556          char buf[100];
01557 
01558          pj_strerror(status, buf, sizeof(buf));
01559          ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
01560             (int) status, buf);
01561          return -1;
01562       }
01563       if (!rtp->passthrough) {
01564          return 0;
01565       }
01566       rtp->passthrough = 0;
01567    }
01568 #endif
01569 
01570    if ((*in & 0xC0) && res_srtp && srtp && res_srtp->unprotect(srtp, buf, &len, rtcp) < 0) {
01571       return -1;
01572    }
01573 
01574    return len;
01575 }
01576 
01577 static int rtcp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
01578 {
01579    return __rtp_recvfrom(instance, buf, size, flags, sa, 1);
01580 }
01581 
01582 static int rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
01583 {
01584    return __rtp_recvfrom(instance, buf, size, flags, sa, 0);
01585 }
01586 
01587 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)
01588 {
01589    int len = size;
01590    void *temp = buf;
01591    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01592    struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
01593 
01594    *ice = 0;
01595 
01596    if (use_srtp && res_srtp && srtp && res_srtp->protect(srtp, &temp, &len, rtcp) < 0) {
01597       return -1;
01598    }
01599 
01600 #ifdef USE_PJPROJECT
01601    if (rtp->ice) {
01602       pj_thread_register_check();
01603 
01604       if (pj_ice_sess_send_data(rtp->ice, rtcp ? AST_RTP_ICE_COMPONENT_RTCP : AST_RTP_ICE_COMPONENT_RTP, temp, len) == PJ_SUCCESS) {
01605          *ice = 1;
01606          return 0;
01607       }
01608    }
01609 #endif
01610 
01611    return ast_sendto(rtcp ? rtp->rtcp->s : rtp->s, temp, len, flags, sa);
01612 }
01613 
01614 static int rtcp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
01615 {
01616    return __rtp_sendto(instance, buf, size, flags, sa, 1, ice, 1);
01617 }
01618 
01619 static int rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
01620 {
01621    return __rtp_sendto(instance, buf, size, flags, sa, 0, ice, 1);
01622 }
01623 
01624 static int rtp_get_rate(struct ast_format *format)
01625 {
01626    return (format->id == AST_FORMAT_G722) ? 8000 : ast_format_rate(format);
01627 }
01628 
01629 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
01630 {
01631    unsigned int interval;
01632    /*! \todo XXX Do a more reasonable calculation on this one
01633     * Look in RFC 3550 Section A.7 for an example*/
01634    interval = rtcpinterval;
01635    return interval;
01636 }
01637 
01638 /*! \brief Calculate normal deviation */
01639 static double normdev_compute(double normdev, double sample, unsigned int sample_count)
01640 {
01641    normdev = normdev * sample_count + sample;
01642    sample_count++;
01643 
01644    return normdev / sample_count;
01645 }
01646 
01647 static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
01648 {
01649 /*
01650       for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
01651       return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
01652       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
01653       optimized formula
01654 */
01655 #define SQUARE(x) ((x) * (x))
01656 
01657    stddev = sample_count * stddev;
01658    sample_count++;
01659 
01660    return stddev +
01661       ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) +
01662       ( SQUARE(sample - normdev_curent) / sample_count );
01663 
01664 #undef SQUARE
01665 }
01666 
01667 static int create_new_socket(const char *type, int af)
01668 {
01669    int sock = socket(af, SOCK_DGRAM, 0);
01670 
01671    if (sock < 0) {
01672       if (!type) {
01673          type = "RTP/RTCP";
01674       }
01675       ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
01676    } else {
01677       long flags = fcntl(sock, F_GETFL);
01678       fcntl(sock, F_SETFL, flags | O_NONBLOCK);
01679 #ifdef SO_NO_CHECK
01680       if (nochecksums) {
01681          setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
01682       }
01683 #endif
01684    }
01685 
01686    return sock;
01687 }
01688 
01689 /*!
01690  * \internal
01691  * \brief Initializes sequence values and probation for learning mode.
01692  * \note This is an adaptation of pjmedia's pjmedia_rtp_seq_init function.
01693  *
01694  * \param info The learning information to track
01695  * \param seq sequence number read from the rtp header to initialize the information with
01696  */
01697 static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq)
01698 {
01699    info->max_seq = seq - 1;
01700    info->packets = learning_min_sequential;
01701 }
01702 
01703 /*!
01704  * \internal
01705  * \brief Updates sequence information for learning mode and determines if probation/learning mode should remain in effect.
01706  * \note This function was adapted from pjmedia's pjmedia_rtp_seq_update function.
01707  *
01708  * \param info Structure tracking the learning progress of some address
01709  * \param seq sequence number read from the rtp header
01710  * \retval 0 if probation mode should exit for this address
01711  * \retval non-zero if probation mode should continue
01712  */
01713 static int rtp_learning_rtp_seq_update(struct rtp_learning_info *info, uint16_t seq)
01714 {
01715    if (seq == info->max_seq + 1) {
01716       /* packet is in sequence */
01717       info->packets--;
01718    } else {
01719       /* Sequence discontinuity; reset */
01720       info->packets = learning_min_sequential - 1;
01721    }
01722    info->max_seq = seq;
01723 
01724    return (info->packets == 0);
01725 }
01726 
01727 #ifdef USE_PJPROJECT
01728 static void rtp_add_candidates_to_ice(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_sockaddr *addr, int port, int component,
01729                   int transport, const pj_turn_sock_cb *turn_cb, pj_turn_sock **turn_sock)
01730 {
01731    pj_sockaddr address[16];
01732    unsigned int count = PJ_ARRAY_SIZE(address), pos = 0;
01733 
01734    /* Add all the local interface IP addresses */
01735    if (ast_sockaddr_is_ipv4(addr)) {
01736       pj_enum_ip_interface(pj_AF_INET(), &count, address);
01737    } else if (ast_sockaddr_is_any(addr)) {
01738       pj_enum_ip_interface(pj_AF_UNSPEC(), &count, address);
01739    } else {
01740       pj_enum_ip_interface(pj_AF_INET6(), &count, address);
01741    }
01742 
01743    for (pos = 0; pos < count; pos++) {
01744       pj_sockaddr_set_port(&address[pos], port);
01745       ast_rtp_ice_add_cand(rtp, component, transport, PJ_ICE_CAND_TYPE_HOST, 65535, &address[pos], &address[pos], NULL,
01746                  pj_sockaddr_get_len(&address[pos]));
01747    }
01748 
01749    /* If configured to use a STUN server to get our external mapped address do so */
01750    if (stunaddr.sin_addr.s_addr && ast_sockaddr_is_ipv4(addr) && count) {
01751       struct sockaddr_in answer;
01752 
01753       if (!ast_stun_request(component == AST_RTP_ICE_COMPONENT_RTCP ? rtp->rtcp->s : rtp->s, &stunaddr, NULL, &answer)) {
01754          pj_sockaddr base;
01755          pj_str_t mapped = pj_str(ast_strdupa(ast_inet_ntoa(answer.sin_addr)));
01756 
01757          /* Use the first local host candidate as the base */
01758          pj_sockaddr_cp(&base, &address[0]);
01759 
01760          pj_sockaddr_init(pj_AF_INET(), &address[0], &mapped, ntohs(answer.sin_port));
01761 
01762          ast_rtp_ice_add_cand(rtp, component, transport, PJ_ICE_CAND_TYPE_SRFLX, 65535, &address[0], &base,
01763                     NULL, pj_sockaddr_get_len(&address[0]));
01764       }
01765    }
01766 
01767    /* If configured to use a TURN relay create a session and allocate */
01768    if (pj_strlen(&turnaddr) && pj_turn_sock_create(&rtp->ice->stun_cfg, ast_sockaddr_is_ipv4(addr) ? pj_AF_INET() : pj_AF_INET6(), PJ_TURN_TP_TCP,
01769                      turn_cb, NULL, instance, turn_sock) == PJ_SUCCESS) {
01770       pj_stun_auth_cred cred = { 0, };
01771       struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_ALLOCATION_WAIT_TIME, 1000));
01772       struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
01773 
01774       cred.type = PJ_STUN_AUTH_CRED_STATIC;
01775       cred.data.static_cred.username = turnusername;
01776       cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
01777       cred.data.static_cred.data = turnpassword;
01778 
01779       /* Because the TURN socket is asynchronous but we are synchronous we need to wait until it is done */
01780       ast_mutex_lock(&rtp->lock);
01781       pj_turn_sock_alloc(*turn_sock, &turnaddr, turnport, NULL, &cred, NULL);
01782       ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
01783       ast_mutex_unlock(&rtp->lock);
01784 
01785       /* If a TURN session was allocated add it as a candidate */
01786       if (rtp->turn_state == PJ_TURN_STATE_READY) {
01787          pj_turn_session_info info;
01788 
01789          pj_turn_sock_get_info(*turn_sock, &info);
01790 
01791          if (transport == TRANSPORT_SOCKET_RTP) {
01792             transport = TRANSPORT_TURN_RTP;
01793          } else if (transport == TRANSPORT_SOCKET_RTCP) {
01794             transport = TRANSPORT_TURN_RTCP;
01795          }
01796 
01797          ast_rtp_ice_add_cand(rtp, component, transport, PJ_ICE_CAND_TYPE_RELAYED, 65535, &info.relay_addr, &info.relay_addr,
01798                     NULL, pj_sockaddr_get_len(&info.relay_addr));
01799       }
01800    }
01801 }
01802 #endif
01803 
01804 /*!
01805  * \internal
01806  * \brief Calculates the elapsed time from issue of the first tx packet in an
01807  *        rtp session and a specified time
01808  *
01809  * \param rtp pointer to the rtp struct with the transmitted rtp packet
01810  * \param delivery time of delivery - if NULL or zero value, will be ast_tvnow()
01811  *
01812  * \return time elapsed in milliseconds
01813  */
01814 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
01815 {
01816    struct timeval t;
01817    long ms;
01818 
01819    if (ast_tvzero(rtp->txcore)) {
01820       rtp->txcore = ast_tvnow();
01821       rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
01822    }
01823 
01824    t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
01825    if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
01826       ms = 0;
01827    }
01828    rtp->txcore = t;
01829 
01830    return (unsigned int) ms;
01831 }
01832 
01833 #ifdef USE_PJPROJECT
01834 /*!
01835  * \internal
01836  * \brief Creates an ICE session. Can be used to replace a destroyed ICE session.
01837  *
01838  * \param instance RTP instance for which the ICE session is being replaced
01839  * \param addr ast_sockaddr to use for adding RTP candidates to the ICE session
01840  * \param port port to use for adding RTP candidates to the ICE session
01841  * \param replace 0 when creating a new session, 1 when replacing a destroyed session
01842  *
01843  * \retval 0 on success
01844  * \retval -1 on failure
01845  */
01846 static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
01847    int port, int replace)
01848 {
01849    pj_stun_config stun_config;
01850    pj_str_t ufrag, passwd;
01851    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01852 
01853    ao2_cleanup(rtp->ice_local_candidates);
01854    rtp->ice_local_candidates = NULL;
01855 
01856    pj_thread_register_check();
01857 
01858    pj_stun_config_init(&stun_config, &cachingpool.factory, 0, ioqueue, timerheap);
01859 
01860    ufrag = pj_str(rtp->local_ufrag);
01861    passwd = pj_str(rtp->local_passwd);
01862 
01863    /* Create an ICE session for ICE negotiation */
01864    if (pj_ice_sess_create(&stun_config, NULL, PJ_ICE_SESS_ROLE_UNKNOWN, 2,
01865          &ast_rtp_ice_sess_cb, &ufrag, &passwd, &rtp->ice) == PJ_SUCCESS) {
01866       /* Make this available for the callbacks */
01867       rtp->ice->user_data = rtp;
01868 
01869       /* Add all of the available candidates to the ICE session */
01870       rtp_add_candidates_to_ice(instance, rtp, addr, port, AST_RTP_ICE_COMPONENT_RTP,
01871          TRANSPORT_SOCKET_RTP, &ast_rtp_turn_rtp_sock_cb, &rtp->turn_rtp);
01872 
01873       /* Only add the RTCP candidates to ICE when replacing the session. New sessions
01874        * handle this in a separate part of the setup phase */
01875       if (replace && rtp->rtcp) {
01876          rtp_add_candidates_to_ice(instance, rtp, &rtp->rtcp->us,
01877             ast_sockaddr_port(&rtp->rtcp->us), AST_RTP_ICE_COMPONENT_RTCP,
01878             TRANSPORT_SOCKET_RTCP, &ast_rtp_turn_rtcp_sock_cb, &rtp->turn_rtcp);
01879       }
01880 
01881       return 0;
01882    }
01883 
01884    return -1;
01885 
01886 }
01887 #endif
01888 
01889 static int ast_rtp_new(struct ast_rtp_instance *instance,
01890              struct ast_sched_context *sched, struct ast_sockaddr *addr,
01891              void *data)
01892 {
01893    struct ast_rtp *rtp = NULL;
01894    int x, startplace;
01895 
01896    /* Create a new RTP structure to hold all of our data */
01897    if (!(rtp = ast_calloc(1, sizeof(*rtp)))) {
01898       return -1;
01899    }
01900 
01901 #ifdef USE_PJPROJECT
01902    /* Initialize synchronization aspects */
01903    ast_mutex_init(&rtp->lock);
01904    ast_cond_init(&rtp->cond, NULL);
01905 #endif
01906 
01907    /* Set default parameters on the newly created RTP structure */
01908    rtp->ssrc = ast_random();
01909    rtp->seqno = ast_random() & 0xffff;
01910    rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
01911    if (strictrtp) {
01912       rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t)rtp->seqno);
01913       rtp_learning_seq_init(&rtp->alt_source_learn, (uint16_t)rtp->seqno);
01914    }
01915 
01916    /* Create a new socket for us to listen on and use */
01917    if ((rtp->s =
01918         create_new_socket("RTP",
01919                 ast_sockaddr_is_ipv4(addr) ? AF_INET  :
01920                 ast_sockaddr_is_ipv6(addr) ? AF_INET6 : -1)) < 0) {
01921       ast_debug(1, "Failed to create a new socket for RTP instance '%p'\n", instance);
01922       ast_free(rtp);
01923       return -1;
01924    }
01925 
01926    /* Now actually find a free RTP port to use */
01927    x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
01928    x = x & ~1;
01929    startplace = x;
01930 
01931    for (;;) {
01932       ast_sockaddr_set_port(addr, x);
01933       /* Try to bind, this will tell us whether the port is available or not */
01934       if (!ast_bind(rtp->s, addr)) {
01935          ast_debug(1, "Allocated port %d for RTP instance '%p'\n", x, instance);
01936          ast_rtp_instance_set_local_address(instance, addr);
01937          break;
01938       }
01939 
01940       x += 2;
01941       if (x > rtpend) {
01942          x = (rtpstart + 1) & ~1;
01943       }
01944 
01945       /* See if we ran out of ports or if the bind actually failed because of something other than the address being in use */
01946       if (x == startplace || (errno != EADDRINUSE && errno != EACCES)) {
01947          ast_log(LOG_ERROR, "Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
01948          close(rtp->s);
01949          ast_free(rtp);
01950          return -1;
01951       }
01952    }
01953 
01954    ast_rtp_instance_set_data(instance, rtp);
01955 
01956 #ifdef USE_PJPROJECT
01957    generate_random_string(rtp->local_ufrag, sizeof(rtp->local_ufrag));
01958    generate_random_string(rtp->local_passwd, sizeof(rtp->local_passwd));
01959 
01960    /* Create an ICE session for ICE negotiation */
01961    if (icesupport) {
01962       if (ice_create(instance, addr, x, 0)) {
01963          ast_log(LOG_NOTICE, "Failed to start ICE session\n");
01964       } else {
01965          rtp->ice_port = x;
01966          ast_sockaddr_copy(&rtp->ice_original_rtp_addr, addr);
01967       }
01968    }
01969 #endif
01970 
01971    /* Record any information we may need */
01972    rtp->sched = sched;
01973 
01974 #ifdef HAVE_OPENSSL_SRTP
01975    rtp->rekeyid = -1;
01976 #endif
01977 
01978    return 0;
01979 }
01980 
01981 static int ast_rtp_destroy(struct ast_rtp_instance *instance)
01982 {
01983    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01984 
01985    /* Destroy the smoother that was smoothing out audio if present */
01986    if (rtp->smoother) {
01987       ast_smoother_free(rtp->smoother);
01988    }
01989 
01990    /* Close our own socket so we no longer get packets */
01991    if (rtp->s > -1) {
01992       close(rtp->s);
01993    }
01994 
01995    /* Destroy RTCP if it was being used */
01996    if (rtp->rtcp) {
01997       /*
01998        * It is not possible for there to be an active RTCP scheduler
01999        * entry at this point since it holds a reference to the
02000        * RTP instance while it's active.
02001        */
02002       close(rtp->rtcp->s);
02003       ast_free(rtp->rtcp);
02004    }
02005 
02006    /* Destroy RED if it was being used */
02007    if (rtp->red) {
02008       AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
02009       ast_free(rtp->red);
02010    }
02011 
02012 #ifdef USE_PJPROJECT
02013    pj_thread_register_check();
02014 
02015    /* Destroy the ICE session if being used */
02016    if (rtp->ice) {
02017       pj_ice_sess_destroy(rtp->ice);
02018    }
02019 
02020    /* Destroy the RTP TURN relay if being used */
02021    if (rtp->turn_rtp) {
02022       pj_turn_sock_set_user_data(rtp->turn_rtp, NULL);
02023       pj_turn_sock_destroy(rtp->turn_rtp);
02024    }
02025 
02026    /* Destroy the RTCP TURN relay if being used */
02027    if (rtp->turn_rtcp) {
02028       pj_turn_sock_set_user_data(rtp->turn_rtcp, NULL);
02029       pj_turn_sock_destroy(rtp->turn_rtcp);
02030    }
02031 
02032    /* Destroy any candidates */
02033    if (rtp->ice_local_candidates) {
02034       ao2_ref(rtp->ice_local_candidates, -1);
02035    }
02036 
02037    if (rtp->ice_active_remote_candidates) {
02038       ao2_ref(rtp->ice_active_remote_candidates, -1);
02039    }
02040 
02041    /* Destroy synchronization items */
02042    ast_mutex_destroy(&rtp->lock);
02043    ast_cond_destroy(&rtp->cond);
02044 #endif
02045 
02046 #ifdef HAVE_OPENSSL_SRTP
02047    /* Destroy the SSL context if present */
02048    if (rtp->ssl_ctx) {
02049       SSL_CTX_free(rtp->ssl_ctx);
02050    }
02051 
02052    /* Destroy the SSL session if present */
02053    if (rtp->ssl) {
02054       SSL_free(rtp->ssl);
02055    }
02056 #endif
02057 
02058    /* Finally destroy ourselves */
02059    ast_free(rtp);
02060 
02061    return 0;
02062 }
02063 
02064 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
02065 {
02066    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02067    rtp->dtmfmode = dtmf_mode;
02068    return 0;
02069 }
02070 
02071 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance)
02072 {
02073    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02074    return rtp->dtmfmode;
02075 }
02076 
02077 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
02078 {
02079    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02080    struct ast_sockaddr remote_address = { {0,} };
02081    int hdrlen = 12, res = 0, i = 0, payload = 101;
02082    char data[256];
02083    unsigned int *rtpheader = (unsigned int*)data;
02084 
02085    ast_rtp_instance_get_remote_address(instance, &remote_address);
02086 
02087    /* If we have no remote address information bail out now */
02088    if (ast_sockaddr_isnull(&remote_address)) {
02089       return -1;
02090    }
02091 
02092    /* Convert given digit into what we want to transmit */
02093    if ((digit <= '9') && (digit >= '0')) {
02094       digit -= '0';
02095    } else if (digit == '*') {
02096       digit = 10;
02097    } else if (digit == '#') {
02098       digit = 11;
02099    } else if ((digit >= 'A') && (digit <= 'D')) {
02100       digit = digit - 'A' + 12;
02101    } else if ((digit >= 'a') && (digit <= 'd')) {
02102       digit = digit - 'a' + 12;
02103    } else {
02104       ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
02105       return -1;
02106    }
02107 
02108    /* Grab the payload that they expect the RFC2833 packet to be received in */
02109    payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, NULL, AST_RTP_DTMF);
02110 
02111    rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
02112    rtp->send_duration = 160;
02113    rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
02114    rtp->lastdigitts = rtp->lastts + rtp->send_duration;
02115 
02116    /* Create the actual packet that we will be sending */
02117    rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
02118    rtpheader[1] = htonl(rtp->lastdigitts);
02119    rtpheader[2] = htonl(rtp->ssrc);
02120 
02121    /* Actually send the packet */
02122    for (i = 0; i < 2; i++) {
02123       int ice;
02124 
02125       rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
02126       res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
02127       if (res < 0) {
02128          ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
02129             ast_sockaddr_stringify(&remote_address),
02130             strerror(errno));
02131       }
02132 #ifdef USE_PJPROJECT
02133       update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
02134 #endif
02135       if (rtp_debug_test_addr(&remote_address)) {
02136          ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
02137                 ast_sockaddr_stringify(&remote_address),
02138                 ice ? " (via ICE)" : "",
02139                 payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
02140       }
02141       rtp->seqno++;
02142       rtp->send_duration += 160;
02143       rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
02144    }
02145 
02146    /* Record that we are in the process of sending a digit and information needed to continue doing so */
02147    rtp->sending_digit = 1;
02148    rtp->send_digit = digit;
02149    rtp->send_payload = payload;
02150 
02151    return 0;
02152 }
02153 
02154 static int ast_rtp_dtmf_continuation(struct ast_rtp_instance *instance)
02155 {
02156    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02157    struct ast_sockaddr remote_address = { {0,} };
02158    int hdrlen = 12, res = 0;
02159    char data[256];
02160    unsigned int *rtpheader = (unsigned int*)data;
02161    int ice;
02162 
02163    ast_rtp_instance_get_remote_address(instance, &remote_address);
02164 
02165    /* Make sure we know where the other side is so we can send them the packet */
02166    if (ast_sockaddr_isnull(&remote_address)) {
02167       return -1;
02168    }
02169 
02170    /* Actually create the packet we will be sending */
02171    rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
02172    rtpheader[1] = htonl(rtp->lastdigitts);
02173    rtpheader[2] = htonl(rtp->ssrc);
02174    rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
02175 
02176    /* Boom, send it on out */
02177    res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
02178    if (res < 0) {
02179       ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
02180          ast_sockaddr_stringify(&remote_address),
02181          strerror(errno));
02182    }
02183 
02184 #ifdef USE_PJPROJECT
02185    update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
02186 #endif
02187 
02188    if (rtp_debug_test_addr(&remote_address)) {
02189       ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
02190              ast_sockaddr_stringify(&remote_address),
02191              ice ? " (via ICE)" : "",
02192              rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
02193    }
02194 
02195    /* And now we increment some values for the next time we swing by */
02196    rtp->seqno++;
02197    rtp->send_duration += 160;
02198    rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
02199 
02200    return 0;
02201 }
02202 
02203 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
02204 {
02205    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02206    struct ast_sockaddr remote_address = { {0,} };
02207    int hdrlen = 12, res = -1, i = 0;
02208    char data[256];
02209    unsigned int *rtpheader = (unsigned int*)data;
02210    unsigned int measured_samples;
02211 
02212    ast_rtp_instance_get_remote_address(instance, &remote_address);
02213 
02214    /* Make sure we know where the remote side is so we can send them the packet we construct */
02215    if (ast_sockaddr_isnull(&remote_address)) {
02216       goto cleanup;
02217    }
02218 
02219    /* Convert the given digit to the one we are going to send */
02220    if ((digit <= '9') && (digit >= '0')) {
02221       digit -= '0';
02222    } else if (digit == '*') {
02223       digit = 10;
02224    } else if (digit == '#') {
02225       digit = 11;
02226    } else if ((digit >= 'A') && (digit <= 'D')) {
02227       digit = digit - 'A' + 12;
02228    } else if ((digit >= 'a') && (digit <= 'd')) {
02229       digit = digit - 'a' + 12;
02230    } else {
02231       ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
02232       goto cleanup;
02233    }
02234 
02235    rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
02236 
02237    if (duration > 0 && (measured_samples = duration * rtp_get_rate(&rtp->f.subclass.format) / 1000) > rtp->send_duration) {
02238       ast_debug(2, "Adjusting final end duration from %u to %u\n", rtp->send_duration, measured_samples);
02239       rtp->send_duration = measured_samples;
02240    }
02241 
02242    /* Construct the packet we are going to send */
02243    rtpheader[1] = htonl(rtp->lastdigitts);
02244    rtpheader[2] = htonl(rtp->ssrc);
02245    rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
02246    rtpheader[3] |= htonl((1 << 23));
02247 
02248    /* Send it 3 times, that's the magical number */
02249    for (i = 0; i < 3; i++) {
02250       int ice;
02251 
02252       rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
02253 
02254       res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
02255 
02256       if (res < 0) {
02257          ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
02258             ast_sockaddr_stringify(&remote_address),
02259             strerror(errno));
02260       }
02261 
02262 #ifdef USE_PJPROJECT
02263       update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
02264 #endif
02265 
02266       if (rtp_debug_test_addr(&remote_address)) {
02267          ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
02268                 ast_sockaddr_stringify(&remote_address),
02269                 ice ? " (via ICE)" : "",
02270                 rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
02271       }
02272 
02273       rtp->seqno++;
02274    }
02275    res = 0;
02276 
02277    /* Oh and we can't forget to turn off the stuff that says we are sending DTMF */
02278    rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
02279 cleanup:
02280    rtp->sending_digit = 0;
02281    rtp->send_digit = 0;
02282 
02283    return res;
02284 }
02285 
02286 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
02287 {
02288    return ast_rtp_dtmf_end_with_duration(instance, digit, 0);
02289 }
02290 
02291 static void ast_rtp_update_source(struct ast_rtp_instance *instance)
02292 {
02293    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02294 
02295    /* We simply set this bit so that the next packet sent will have the marker bit turned on */
02296    ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
02297    ast_debug(3, "Setting the marker bit due to a source update\n");
02298 
02299    return;
02300 }
02301 
02302 static void ast_rtp_change_source(struct ast_rtp_instance *instance)
02303 {
02304    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02305    struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
02306    unsigned int ssrc = ast_random();
02307 
02308    if (!rtp->lastts) {
02309       ast_debug(3, "Not changing SSRC since we haven't sent any RTP yet\n");
02310       return;
02311    }
02312 
02313    /* We simply set this bit so that the next packet sent will have the marker bit turned on */
02314    ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
02315 
02316    ast_debug(3, "Changing ssrc from %u to %u due to a source change\n", rtp->ssrc, ssrc);
02317 
02318    if (srtp) {
02319       ast_debug(3, "Changing ssrc for SRTP from %u to %u\n", rtp->ssrc, ssrc);
02320       res_srtp->change_source(srtp, rtp->ssrc, ssrc);
02321    }
02322 
02323    rtp->ssrc = ssrc;
02324 
02325    return;
02326 }
02327 
02328 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
02329 {
02330    unsigned int sec, usec, frac;
02331    sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
02332    usec = tv.tv_usec;
02333    frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
02334    *msw = sec;
02335    *lsw = frac;
02336 }
02337 
02338 /*! \brief Send RTCP recipient's report */
02339 static int ast_rtcp_write_rr(struct ast_rtp_instance *instance)
02340 {
02341    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02342    int res;
02343    int len = 32;
02344    unsigned int lost;
02345    unsigned int extended;
02346    unsigned int expected;
02347    unsigned int expected_interval;
02348    unsigned int received_interval;
02349    int lost_interval;
02350    struct timeval now;
02351    unsigned int *rtcpheader;
02352    char bdata[1024];
02353    struct timeval dlsr;
02354    int fraction;
02355    int rate = rtp_get_rate(&rtp->f.subclass.format);
02356    int ice;
02357    double rxlost_current;
02358    struct ast_sockaddr remote_address = { {0,} };
02359 
02360    if (!rtp || !rtp->rtcp)
02361       return 0;
02362 
02363    if (ast_sockaddr_isnull(&rtp->rtcp->them)) {
02364       /*
02365        * RTCP was stopped.
02366        */
02367       return 0;
02368    }
02369 
02370    extended = rtp->cycles + rtp->lastrxseqno;
02371    expected = extended - rtp->seedrxseqno + 1;
02372    lost = expected - rtp->rxcount;
02373    expected_interval = expected - rtp->rtcp->expected_prior;
02374    rtp->rtcp->expected_prior = expected;
02375    received_interval = rtp->rxcount - rtp->rtcp->received_prior;
02376    rtp->rtcp->received_prior = rtp->rxcount;
02377    lost_interval = expected_interval - received_interval;
02378 
02379    if (lost_interval <= 0)
02380       rtp->rtcp->rxlost = 0;
02381    else rtp->rtcp->rxlost = rtp->rtcp->rxlost;
02382    if (rtp->rtcp->rxlost_count == 0)
02383       rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
02384    if (lost_interval < rtp->rtcp->minrxlost)
02385       rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
02386    if (lost_interval > rtp->rtcp->maxrxlost)
02387       rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
02388 
02389    rxlost_current = normdev_compute(rtp->rtcp->normdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->rxlost_count);
02390    rtp->rtcp->stdev_rxlost = stddev_compute(rtp->rtcp->stdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->normdev_rxlost, rxlost_current, rtp->rtcp->rxlost_count);
02391    rtp->rtcp->normdev_rxlost = rxlost_current;
02392    rtp->rtcp->rxlost_count++;
02393 
02394    if (expected_interval == 0 || lost_interval <= 0)
02395       fraction = 0;
02396    else
02397       fraction = (lost_interval << 8) / expected_interval;
02398    gettimeofday(&now, NULL);
02399    timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
02400    rtcpheader = (unsigned int *)bdata;
02401    rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
02402    rtcpheader[1] = htonl(rtp->ssrc);
02403    rtcpheader[2] = htonl(rtp->themssrc);
02404    rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
02405    rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
02406    rtcpheader[5] = htonl((unsigned int)(rtp->rxjitter * rate));
02407    rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
02408    rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
02409 
02410    /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
02411      it can change mid call, and SDES can't) */
02412    rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
02413    rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
02414    rtcpheader[(len/4)+2] = htonl(0x01 << 24);              /* Empty for the moment */
02415    len += 12;
02416 
02417    ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
02418 
02419    res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &remote_address, &ice);
02420 
02421    if (res < 0) {
02422       ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
02423       return 0;
02424    }
02425 
02426    rtp->rtcp->rr_count++;
02427 
02428 #ifdef USE_PJPROJECT
02429    update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTCP, &remote_address);
02430 #endif
02431 
02432    if (rtcp_debug_test_addr(&remote_address)) {
02433       ast_verbose("\n* Sending RTCP RR to %s%s\n"
02434          "  Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
02435          "  IA jitter: %.4f\n"
02436          "  Their last SR: %u\n"
02437              "  DLSR: %4.4f (sec)\n\n",
02438              ast_sockaddr_stringify(&remote_address),
02439              ice ? " (via ICE)" : "",
02440              rtp->ssrc, rtp->themssrc, fraction, lost,
02441              rtp->rxjitter,
02442              rtp->rtcp->themrxlsr,
02443              (double)(ntohl(rtcpheader[7])/65536.0));
02444    }
02445 
02446    return res;
02447 }
02448 
02449 /*! \brief Send RTCP sender's report */
02450 static int ast_rtcp_write_sr(struct ast_rtp_instance *instance)
02451 {
02452    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02453    int res;
02454    int len = 0;
02455    struct timeval now;
02456    unsigned int now_lsw;
02457    unsigned int now_msw;
02458    unsigned int *rtcpheader;
02459    unsigned int lost;
02460    unsigned int extended;
02461    unsigned int expected;
02462    unsigned int expected_interval;
02463    unsigned int received_interval;
02464    int lost_interval;
02465    int fraction;
02466    struct timeval dlsr;
02467    char bdata[512];
02468    int rate = rtp_get_rate(&rtp->f.subclass.format);
02469    int ice;
02470    struct ast_sockaddr remote_address = { {0,} };
02471 
02472    if (!rtp || !rtp->rtcp)
02473       return 0;
02474 
02475    if (ast_sockaddr_isnull(&rtp->rtcp->them)) {  /* This'll stop rtcp for this rtp session */
02476       /*
02477        * RTCP was stopped.
02478        */
02479       return 0;
02480    }
02481 
02482    gettimeofday(&now, NULL);
02483    timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
02484    rtcpheader = (unsigned int *)bdata;
02485    rtcpheader[1] = htonl(rtp->ssrc);               /* Our SSRC */
02486    rtcpheader[2] = htonl(now_msw);                 /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
02487    rtcpheader[3] = htonl(now_lsw);                 /* now, LSW */
02488    rtcpheader[4] = htonl(rtp->lastts);             /* FIXME shouldn't be that, it should be now */
02489    rtcpheader[5] = htonl(rtp->txcount);            /* No. packets sent */
02490    rtcpheader[6] = htonl(rtp->txoctetcount);       /* No. bytes sent */
02491    len += 28;
02492 
02493    extended = rtp->cycles + rtp->lastrxseqno;
02494    expected = extended - rtp->seedrxseqno + 1;
02495    if (rtp->rxcount > expected)
02496       expected += rtp->rxcount - expected;
02497    lost = expected - rtp->rxcount;
02498    expected_interval = expected - rtp->rtcp->expected_prior;
02499    rtp->rtcp->expected_prior = expected;
02500    received_interval = rtp->rxcount - rtp->rtcp->received_prior;
02501    rtp->rtcp->received_prior = rtp->rxcount;
02502    lost_interval = expected_interval - received_interval;
02503    if (expected_interval == 0 || lost_interval <= 0)
02504       fraction = 0;
02505    else
02506       fraction = (lost_interval << 8) / expected_interval;
02507    timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
02508    rtcpheader[7] = htonl(rtp->themssrc);
02509    rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
02510    rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
02511    rtcpheader[10] = htonl((unsigned int)(rtp->rxjitter * rate));
02512    rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
02513    rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
02514    len += 24;
02515 
02516    rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
02517 
02518    /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
02519    /* it can change mid call, and SDES can't) */
02520    rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
02521    rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
02522    rtcpheader[(len/4)+2] = htonl(0x01 << 24);                    /* Empty for the moment */
02523    len += 12;
02524 
02525    ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
02526 
02527    res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &remote_address, &ice);
02528    if (res < 0) {
02529       ast_log(LOG_ERROR, "RTCP SR transmission error to %s, rtcp halted %s\n",
02530          ast_sockaddr_stringify(&rtp->rtcp->them),
02531          strerror(errno));
02532       return 0;
02533    }
02534 
02535    /* FIXME Don't need to get a new one */
02536    gettimeofday(&rtp->rtcp->txlsr, NULL);
02537    rtp->rtcp->sr_count++;
02538 
02539    rtp->rtcp->lastsrtxcount = rtp->txcount;
02540 
02541 #ifdef USE_PJPROJECT
02542    update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTCP, &remote_address);
02543 #endif
02544 
02545    if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
02546       ast_verbose("* Sent RTCP SR to %s%s\n", ast_sockaddr_stringify(&remote_address), ice ? " (via ICE)" : "");
02547       ast_verbose("  Our SSRC: %u\n", rtp->ssrc);
02548       ast_verbose("  Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
02549       ast_verbose("  Sent(RTP): %u\n", rtp->lastts);
02550       ast_verbose("  Sent packets: %u\n", rtp->txcount);
02551       ast_verbose("  Sent octets: %u\n", rtp->txoctetcount);
02552       ast_verbose("  Report block:\n");
02553       ast_verbose("  Fraction lost: %u\n", fraction);
02554       ast_verbose("  Cumulative loss: %u\n", lost);
02555       ast_verbose("  IA jitter: %.4f\n", rtp->rxjitter);
02556       ast_verbose("  Their last SR: %u\n", rtp->rtcp->themrxlsr);
02557       ast_verbose("  DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
02558    }
02559    manager_event(EVENT_FLAG_REPORTING, "RTCPSent", "To: %s\r\n"
02560                    "OurSSRC: %u\r\n"
02561                    "SentNTP: %u.%010u\r\n"
02562                    "SentRTP: %u\r\n"
02563                    "SentPackets: %u\r\n"
02564                    "SentOctets: %u\r\n"
02565                    "ReportBlock:\r\n"
02566                    "FractionLost: %u\r\n"
02567                    "CumulativeLoss: %u\r\n"
02568                    "IAJitter: %.4f\r\n"
02569                    "TheirLastSR: %u\r\n"
02570             "DLSR: %4.4f (sec)\r\n",
02571             ast_sockaddr_stringify(&remote_address),
02572             rtp->ssrc,
02573             (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096,
02574             rtp->lastts,
02575             rtp->txcount,
02576             rtp->txoctetcount,
02577             fraction,
02578             lost,
02579             rtp->rxjitter,
02580             rtp->rtcp->themrxlsr,
02581             (double)(ntohl(rtcpheader[12])/65536.0));
02582    return res;
02583 }
02584 
02585 /*! \brief Write and RTCP packet to the far end
02586  * \note Decide if we are going to send an SR (with Reception Block) or RR
02587  * RR is sent if we have not sent any rtp packets in the previous interval */
02588 static int ast_rtcp_write(const void *data)
02589 {
02590    struct ast_rtp_instance *instance = (struct ast_rtp_instance *) data;
02591    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02592    int res;
02593 
02594    if (!rtp || !rtp->rtcp || rtp->rtcp->schedid == -1) {
02595       ao2_ref(instance, -1);
02596       return 0;
02597    }
02598 
02599    if (rtp->txcount > rtp->rtcp->lastsrtxcount) {
02600       res = ast_rtcp_write_sr(instance);
02601    } else {
02602       res = ast_rtcp_write_rr(instance);
02603    }
02604 
02605    if (!res) {
02606       /* 
02607        * Not being rescheduled.
02608        */
02609       ao2_ref(instance, -1);
02610       rtp->rtcp->schedid = -1;
02611    }
02612 
02613    return res;
02614 }
02615 
02616 static int ast_rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
02617 {
02618    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02619    int pred, mark = 0;
02620    unsigned int ms = calc_txstamp(rtp, &frame->delivery);
02621    struct ast_sockaddr remote_address = { {0,} };
02622    int rate = rtp_get_rate(&frame->subclass.format) / 1000;
02623 
02624    if (frame->subclass.format.id == AST_FORMAT_G722) {
02625       frame->samples /= 2;
02626    }
02627 
02628    if (rtp->sending_digit) {
02629       return 0;
02630    }
02631 
02632    if (frame->frametype == AST_FRAME_VOICE) {
02633       pred = rtp->lastts + frame->samples;
02634 
02635       /* Re-calculate last TS */
02636       rtp->lastts = rtp->lastts + ms * rate;
02637       if (ast_tvzero(frame->delivery)) {
02638          /* If this isn't an absolute delivery time, Check if it is close to our prediction,
02639             and if so, go with our prediction */
02640          if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW) {
02641             rtp->lastts = pred;
02642          } else {
02643             ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
02644             mark = 1;
02645          }
02646       }
02647    } else if (frame->frametype == AST_FRAME_VIDEO) {
02648       mark = ast_format_get_video_mark(&frame->subclass.format);
02649       pred = rtp->lastovidtimestamp + frame->samples;
02650       /* Re-calculate last TS */
02651       rtp->lastts = rtp->lastts + ms * 90;
02652       /* If it's close to our prediction, go for it */
02653       if (ast_tvzero(frame->delivery)) {
02654          if (abs(rtp->lastts - pred) < 7200) {
02655             rtp->lastts = pred;
02656             rtp->lastovidtimestamp += frame->samples;
02657          } else {
02658             ast_debug(3, "Difference is %d, ms is %d (%d), pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, frame->samples);
02659             rtp->lastovidtimestamp = rtp->lastts;
02660          }
02661       }
02662    } else {
02663       pred = rtp->lastotexttimestamp + frame->samples;
02664       /* Re-calculate last TS */
02665       rtp->lastts = rtp->lastts + ms;
02666       /* If it's close to our prediction, go for it */
02667       if (ast_tvzero(frame->delivery)) {
02668          if (abs(rtp->lastts - pred) < 7200) {
02669             rtp->lastts = pred;
02670             rtp->lastotexttimestamp += frame->samples;
02671          } else {
02672             ast_debug(3, "Difference is %d, ms is %d, pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, rtp->lastts, pred, frame->samples);
02673             rtp->lastotexttimestamp = rtp->lastts;
02674          }
02675       }
02676    }
02677 
02678    /* If we have been explicitly told to set the marker bit then do so */
02679    if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
02680       mark = 1;
02681       ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
02682    }
02683 
02684    /* If the timestamp for non-digt packets has moved beyond the timestamp for digits, update the digit timestamp */
02685    if (rtp->lastts > rtp->lastdigitts) {
02686       rtp->lastdigitts = rtp->lastts;
02687    }
02688 
02689    if (ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO)) {
02690       rtp->lastts = frame->ts * rate;
02691    }
02692 
02693    ast_rtp_instance_get_remote_address(instance, &remote_address);
02694 
02695    /* If we know the remote address construct a packet and send it out */
02696    if (!ast_sockaddr_isnull(&remote_address)) {
02697       int hdrlen = 12, res, ice;
02698       unsigned char *rtpheader = (unsigned char *)(frame->data.ptr - hdrlen);
02699 
02700       put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
02701       put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
02702       put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
02703 
02704       if ((res = rtp_sendto(instance, (void *)rtpheader, frame->datalen + hdrlen, 0, &remote_address, &ice)) < 0) {
02705          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))) {
02706             ast_debug(1, "RTP Transmission error of packet %d to %s: %s\n",
02707                  rtp->seqno,
02708                  ast_sockaddr_stringify(&remote_address),
02709                  strerror(errno));
02710          } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
02711             /* Only give this error message once if we are not RTP debugging */
02712             if (rtpdebug)
02713                ast_debug(0, "RTP NAT: Can't write RTP to private address %s, waiting for other end to send audio...\n",
02714                     ast_sockaddr_stringify(&remote_address));
02715             ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
02716          }
02717       } else {
02718          rtp->txcount++;
02719          rtp->txoctetcount += (res - hdrlen);
02720 
02721          if (rtp->rtcp && rtp->rtcp->schedid < 1) {
02722             ast_debug(1, "Starting RTCP transmission on RTP instance '%p'\n", instance);
02723             ao2_ref(instance, +1);
02724             rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, instance);
02725             if (rtp->rtcp->schedid < 0) {
02726                ao2_ref(instance, -1);
02727                ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
02728             }
02729          }
02730       }
02731 
02732 #ifdef USE_PJPROJECT
02733       update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
02734 #endif
02735 
02736       if (rtp_debug_test_addr(&remote_address)) {
02737          ast_verbose("Sent RTP packet to      %s%s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
02738                 ast_sockaddr_stringify(&remote_address),
02739                 ice ? " (via ICE)" : "",
02740                 codec, rtp->seqno, rtp->lastts, res - hdrlen);
02741       }
02742    }
02743 
02744    rtp->seqno++;
02745 
02746    return 0;
02747 }
02748 
02749 static struct ast_frame *red_t140_to_red(struct rtp_red *red) {
02750    unsigned char *data = red->t140red.data.ptr;
02751    int len = 0;
02752    int i;
02753 
02754    /* replace most aged generation */
02755    if (red->len[0]) {
02756       for (i = 1; i < red->num_gen+1; i++)
02757          len += red->len[i];
02758 
02759       memmove(&data[red->hdrlen], &data[red->hdrlen+red->len[0]], len);
02760    }
02761 
02762    /* Store length of each generation and primary data length*/
02763    for (i = 0; i < red->num_gen; i++)
02764       red->len[i] = red->len[i+1];
02765    red->len[i] = red->t140.datalen;
02766 
02767    /* write each generation length in red header */
02768    len = red->hdrlen;
02769    for (i = 0; i < red->num_gen; i++)
02770       len += data[i*4+3] = red->len[i];
02771 
02772    /* add primary data to buffer */
02773    memcpy(&data[len], red->t140.data.ptr, red->t140.datalen);
02774    red->t140red.datalen = len + red->t140.datalen;
02775 
02776    /* no primary data and no generations to send */
02777    if (len == red->hdrlen && !red->t140.datalen)
02778       return NULL;
02779 
02780    /* reset t.140 buffer */
02781    red->t140.datalen = 0;
02782 
02783    return &red->t140red;
02784 }
02785 
02786 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
02787 {
02788    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02789    struct ast_sockaddr remote_address = { {0,} };
02790    struct ast_format subclass;
02791    int codec;
02792 
02793    ast_rtp_instance_get_remote_address(instance, &remote_address);
02794 
02795    /* If we don't actually know the remote address don't even bother doing anything */
02796    if (ast_sockaddr_isnull(&remote_address)) {
02797       ast_debug(1, "No remote address on RTP instance '%p' so dropping frame\n", instance);
02798       return 0;
02799    }
02800 
02801    /* If there is no data length we can't very well send the packet */
02802    if (!frame->datalen) {
02803       ast_debug(1, "Received frame with no data for RTP instance '%p' so dropping frame\n", instance);
02804       return 0;
02805    }
02806 
02807    /* If the packet is not one our RTP stack supports bail out */
02808    if (frame->frametype != AST_FRAME_VOICE && frame->frametype != AST_FRAME_VIDEO && frame->frametype != AST_FRAME_TEXT) {
02809       ast_log(LOG_WARNING, "RTP can only send voice, video, and text\n");
02810       return -1;
02811    }
02812 
02813    if (rtp->red) {
02814       /* return 0; */
02815       /* no primary data or generations to send */
02816       if ((frame = red_t140_to_red(rtp->red)) == NULL)
02817          return 0;
02818    }
02819 
02820    /* Grab the subclass and look up the payload we are going to use */
02821    ast_format_copy(&subclass, &frame->subclass.format);
02822    if ((codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 1, &subclass, 0)) < 0) {
02823       ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(&frame->subclass.format));
02824       return -1;
02825    }
02826 
02827    /* Oh dear, if the format changed we will have to set up a new smoother */
02828    if (ast_format_cmp(&rtp->lasttxformat, &subclass) == AST_FORMAT_CMP_NOT_EQUAL) {
02829       ast_debug(1, "Ooh, format changed from %s to %s\n", ast_getformatname(&rtp->lasttxformat), ast_getformatname(&subclass));
02830       rtp->lasttxformat = subclass;
02831       ast_format_copy(&rtp->lasttxformat, &subclass);
02832       if (rtp->smoother) {
02833          ast_smoother_free(rtp->smoother);
02834          rtp->smoother = NULL;
02835       }
02836    }
02837 
02838    /* If no smoother is present see if we have to set one up */
02839    if (!rtp->smoother) {
02840       struct ast_format_list fmt = ast_codec_pref_getsize(&ast_rtp_instance_get_codecs(instance)->pref, &subclass);
02841 
02842       switch (subclass.id) {
02843       case AST_FORMAT_SPEEX:
02844       case AST_FORMAT_SPEEX16:
02845       case AST_FORMAT_SPEEX32:
02846       case AST_FORMAT_SILK:
02847       case AST_FORMAT_CELT:
02848       case AST_FORMAT_G723_1:
02849       case AST_FORMAT_SIREN7:
02850       case AST_FORMAT_SIREN14:
02851       case AST_FORMAT_G719:
02852          /* these are all frame-based codecs and cannot be safely run through
02853             a smoother */
02854          break;
02855       default:
02856          if (fmt.inc_ms) {
02857             if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
02858                ast_log(LOG_WARNING, "Unable to create smoother: format %s ms: %d len: %d\n", ast_getformatname(&subclass), fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
02859                return -1;
02860             }
02861             if (fmt.flags) {
02862                ast_smoother_set_flags(rtp->smoother, fmt.flags);
02863             }
02864             ast_debug(1, "Created smoother: format: %s ms: %d len: %d\n", ast_getformatname(&subclass), fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
02865          }
02866       }
02867    }
02868 
02869    /* Feed audio frames into the actual function that will create a frame and send it */
02870    if (rtp->smoother) {
02871       struct ast_frame *f;
02872 
02873       if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
02874          ast_smoother_feed_be(rtp->smoother, frame);
02875       } else {
02876          ast_smoother_feed(rtp->smoother, frame);
02877       }
02878 
02879       while ((f = ast_smoother_read(rtp->smoother)) && (f->data.ptr)) {
02880             ast_rtp_raw_write(instance, f, codec);
02881       }
02882    } else {
02883       int hdrlen = 12;
02884       struct ast_frame *f = NULL;
02885 
02886       if (frame->offset < hdrlen) {
02887          f = ast_frdup(frame);
02888       } else {
02889          f = frame;
02890       }
02891       if (f->data.ptr) {
02892          ast_rtp_raw_write(instance, f, codec);
02893       }
02894       if (f != frame) {
02895          ast_frfree(f);
02896       }
02897 
02898    }
02899 
02900    return 0;
02901 }
02902 
02903 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
02904 {
02905    struct timeval now;
02906    struct timeval tmp;
02907    double transit;
02908    double current_time;
02909    double d;
02910    double dtv;
02911    double prog;
02912    int rate = rtp_get_rate(&rtp->f.subclass.format);
02913 
02914    double normdev_rxjitter_current;
02915    if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
02916       gettimeofday(&rtp->rxcore, NULL);
02917       rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
02918       /* map timestamp to a real time */
02919       rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
02920       tmp = ast_samp2tv(timestamp, rate);
02921       rtp->rxcore = ast_tvsub(rtp->rxcore, tmp);
02922       /* Round to 0.1ms for nice, pretty timestamps */
02923       rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
02924    }
02925 
02926    gettimeofday(&now,NULL);
02927    /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
02928    tmp = ast_samp2tv(timestamp, rate);
02929    *tv = ast_tvadd(rtp->rxcore, tmp);
02930 
02931    prog = (double)((timestamp-rtp->seedrxts)/(float)(rate));
02932    dtv = (double)rtp->drxcore + (double)(prog);
02933    current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
02934    transit = current_time - dtv;
02935    d = transit - rtp->rxtransit;
02936    rtp->rxtransit = transit;
02937    if (d<0)
02938       d=-d;
02939    rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
02940 
02941    if (rtp->rtcp) {
02942       if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
02943          rtp->rtcp->maxrxjitter = rtp->rxjitter;
02944       if (rtp->rtcp->rxjitter_count == 1)
02945          rtp->rtcp->minrxjitter = rtp->rxjitter;
02946       if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
02947          rtp->rtcp->minrxjitter = rtp->rxjitter;
02948 
02949       normdev_rxjitter_current = normdev_compute(rtp->rtcp->normdev_rxjitter,rtp->rxjitter,rtp->rtcp->rxjitter_count);
02950       rtp->rtcp->stdev_rxjitter = stddev_compute(rtp->rtcp->stdev_rxjitter,rtp->rxjitter,rtp->rtcp->normdev_rxjitter,normdev_rxjitter_current,rtp->rtcp->rxjitter_count);
02951 
02952       rtp->rtcp->normdev_rxjitter = normdev_rxjitter_current;
02953       rtp->rtcp->rxjitter_count++;
02954    }
02955 }
02956 
02957 static struct ast_frame *create_dtmf_frame(struct ast_rtp_instance *instance, enum ast_frame_type type, int compensate)
02958 {
02959    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02960    struct ast_sockaddr remote_address = { {0,} };
02961 
02962    ast_rtp_instance_get_remote_address(instance, &remote_address);
02963 
02964    if (((compensate && type == AST_FRAME_DTMF_END) || (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
02965       ast_debug(1, "Ignore potential DTMF echo from '%s'\n",
02966            ast_sockaddr_stringify(&remote_address));
02967       rtp->resp = 0;
02968       rtp->dtmfsamples = 0;
02969       return &ast_null_frame;
02970    }
02971    ast_debug(1, "Creating %s DTMF Frame: %d (%c), at %s\n",
02972       type == AST_FRAME_DTMF_END ? "END" : "BEGIN",
02973       rtp->resp, rtp->resp,
02974       ast_sockaddr_stringify(&remote_address));
02975    if (rtp->resp == 'X') {
02976       rtp->f.frametype = AST_FRAME_CONTROL;
02977       rtp->f.subclass.integer = AST_CONTROL_FLASH;
02978    } else {
02979       rtp->f.frametype = type;
02980       rtp->f.subclass.integer = rtp->resp;
02981    }
02982    rtp->f.datalen = 0;
02983    rtp->f.samples = 0;
02984    rtp->f.mallocd = 0;
02985    rtp->f.src = "RTP";
02986    AST_LIST_NEXT(&rtp->f, frame_list) = NULL;
02987 
02988    return &rtp->f;
02989 }
02990 
02991 static void process_dtmf_rfc2833(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct ast_sockaddr *addr, int payloadtype, int mark, struct frame_list *frames)
02992 {
02993    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02994    struct ast_sockaddr remote_address = { {0,} };
02995    unsigned int event, event_end, samples;
02996    char resp = 0;
02997    struct ast_frame *f = NULL;
02998 
02999    ast_rtp_instance_get_remote_address(instance, &remote_address);
03000 
03001    /* Figure out event, event end, and samples */
03002    event = ntohl(*((unsigned int *)(data)));
03003    event >>= 24;
03004    event_end = ntohl(*((unsigned int *)(data)));
03005    event_end <<= 8;
03006    event_end >>= 24;
03007    samples = ntohl(*((unsigned int *)(data)));
03008    samples &= 0xFFFF;
03009 
03010    if (rtp_debug_test_addr(&remote_address)) {
03011       ast_verbose("Got  RTP RFC2833 from   %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u, mark %d, event %08x, end %d, duration %-5.5d) \n",
03012              ast_sockaddr_stringify(&remote_address),
03013              payloadtype, seqno, timestamp, len, (mark?1:0), event, ((event_end & 0x80)?1:0), samples);
03014    }
03015 
03016    /* Print out debug if turned on */
03017    if (rtpdebug)
03018       ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
03019 
03020    /* Figure out what digit was pressed */
03021    if (event < 10) {
03022       resp = '0' + event;
03023    } else if (event < 11) {
03024       resp = '*';
03025    } else if (event < 12) {
03026       resp = '#';
03027    } else if (event < 16) {
03028       resp = 'A' + (event - 12);
03029    } else if (event < 17) {        /* Event 16: Hook flash */
03030       resp = 'X';
03031    } else {
03032       /* Not a supported event */
03033       ast_debug(1, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
03034       return;
03035    }
03036 
03037    if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
03038       if ((rtp->last_end_timestamp != timestamp) || (rtp->resp && rtp->resp != resp)) {
03039          rtp->resp = resp;
03040          rtp->dtmf_timeout = 0;
03041          f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)));
03042          f->len = 0;
03043          rtp->last_end_timestamp = timestamp;
03044          AST_LIST_INSERT_TAIL(frames, f, frame_list);
03045       }
03046    } else {
03047       /*  The duration parameter measures the complete
03048           duration of the event (from the beginning) - RFC2833.
03049           Account for the fact that duration is only 16 bits long
03050           (about 8 seconds at 8000 Hz) and can wrap is digit
03051           is hold for too long. */
03052       unsigned int new_duration = rtp->dtmf_duration;
03053       unsigned int last_duration = new_duration & 0xFFFF;
03054 
03055       if (last_duration > 64000 && samples < last_duration) {
03056          new_duration += 0xFFFF + 1;
03057       }
03058       new_duration = (new_duration & ~0xFFFF) | samples;
03059 
03060       if (event_end & 0x80) {
03061          if ((seqno != rtp->last_seqno) && (timestamp > rtp->last_end_timestamp)) {
03062             rtp->last_end_timestamp = timestamp;
03063             rtp->dtmf_duration = new_duration;
03064             rtp->resp = resp;
03065             f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
03066             f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(&f->subclass.format)), ast_tv(0, 0));
03067             rtp->resp = 0;
03068             rtp->dtmf_duration = rtp->dtmf_timeout = 0;
03069             AST_LIST_INSERT_TAIL(frames, f, frame_list);
03070          } else if (rtpdebug) {
03071             ast_debug(1, "Dropping re-transmitted, duplicate, or out of order DTMF END frame (seqno: %d, ts %d, digit %c)\n",
03072                seqno, timestamp, resp);
03073          }
03074       } else {
03075          /* Begin/continuation */
03076 
03077          /* The second portion of the seqno check is to not mistakenly
03078           * stop accepting DTMF if the seqno rolls over beyond
03079           * 65535.
03080           */
03081          if ((rtp->last_seqno > seqno && rtp->last_seqno - seqno < 50)
03082             || timestamp <= rtp->last_end_timestamp) {
03083             /* Out of order frame. Processing this can cause us to
03084              * improperly duplicate incoming DTMF, so just drop
03085              * this.
03086              */
03087             if (rtpdebug) {
03088                ast_debug(1, "Dropping out of order DTMF frame (seqno %d, ts %d, digit %c)\n",
03089                   seqno, timestamp, resp);
03090             }
03091             return;
03092          }
03093 
03094          if (rtp->resp && rtp->resp != resp) {
03095             /* Another digit already began. End it */
03096             f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
03097             f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(&f->subclass.format)), ast_tv(0, 0));
03098             rtp->resp = 0;
03099             rtp->dtmf_duration = rtp->dtmf_timeout = 0;
03100             AST_LIST_INSERT_TAIL(frames, f, frame_list);
03101          }
03102 
03103          if (rtp->resp) {
03104             /* Digit continues */
03105             rtp->dtmf_duration = new_duration;
03106          } else {
03107             /* New digit began */
03108             rtp->resp = resp;
03109             f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_BEGIN, 0));
03110             rtp->dtmf_duration = samples;
03111             AST_LIST_INSERT_TAIL(frames, f, frame_list);
03112          }
03113 
03114          rtp->dtmf_timeout = timestamp + rtp->dtmf_duration + dtmftimeout;
03115       }
03116 
03117       rtp->last_seqno = seqno;
03118    }
03119 
03120    rtp->dtmfsamples = samples;
03121 
03122    return;
03123 }
03124 
03125 static struct ast_frame *process_dtmf_cisco(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct ast_sockaddr *addr, int payloadtype, int mark)
03126 {
03127    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
03128    unsigned int event, flags, power;
03129    char resp = 0;
03130    unsigned char seq;
03131    struct ast_frame *f = NULL;
03132 
03133    if (len < 4) {
03134       return NULL;
03135    }
03136 
03137    /*      The format of Cisco RTP DTMF packet looks like next:
03138       +0                              - sequence number of DTMF RTP packet (begins from 1,
03139                     wrapped to 0)
03140       +1                              - set of flags
03141       +1 (bit 0)              - flaps by different DTMF digits delimited by audio
03142                     or repeated digit without audio???
03143       +2 (+4,+6,...)  - power level? (rises from 0 to 32 at begin of tone
03144                     then falls to 0 at its end)
03145       +3 (+5,+7,...)  - detected DTMF digit (0..9,*,#,A-D,...)
03146       Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
03147       by each new packet and thus provides some redudancy.
03148 
03149       Sample of Cisco RTP DTMF packet is (all data in hex):
03150          19 07 00 02 12 02 20 02
03151       showing end of DTMF digit '2'.
03152 
03153       The packets
03154          27 07 00 02 0A 02 20 02
03155          28 06 20 02 00 02 0A 02
03156       shows begin of new digit '2' with very short pause (20 ms) after
03157       previous digit '2'. Bit +1.0 flips at begin of new digit.
03158 
03159       Cisco RTP DTMF packets comes as replacement of audio RTP packets
03160       so its uses the same sequencing and timestamping rules as replaced
03161       audio packets. Repeat interval of DTMF packets is 20 ms and not rely
03162       on audio framing parameters. Marker bit isn't used within stream of
03163       DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
03164       are not sequential at borders between DTMF and audio streams,
03165    */
03166 
03167    seq = data[0];
03168    flags = data[1];
03169    power = data[2];
03170    event = data[3] & 0x1f;
03171 
03172    if (rtpdebug)
03173       ast_debug(0, "Cisco DTMF Digit: %02x (len=%d, seq=%d, flags=%02x, power=%d, history count=%d)\n", event, len, seq, flags, power, (len - 4) / 2);
03174    if (event < 10) {
03175       resp = '0' + event;
03176    } else if (event < 11) {
03177       resp = '*';
03178    } else if (event < 12) {
03179       resp = '#';
03180    } else if (event < 16) {
03181       resp = 'A' + (event - 12);
03182    } else if (event < 17) {
03183       resp = 'X';
03184    }
03185    if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
03186       rtp->resp = resp;
03187       /* Why we should care on DTMF compensation at reception? */
03188       if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
03189          f = create_dtmf_frame(instance, AST_FRAME_DTMF_BEGIN, 0);
03190          rtp->dtmfsamples = 0;
03191       }
03192    } else if ((rtp->resp == resp) && !power) {
03193       f = create_dtmf_frame(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE));
03194       f->samples = rtp->dtmfsamples * (rtp->lastrxformat.id ? (rtp_get_rate(&rtp->lastrxformat) / 1000) : 8);
03195       rtp->resp = 0;
03196    } else if (rtp->resp == resp)
03197       rtp->dtmfsamples += 20 * (rtp->lastrxformat.id ? (rtp_get_rate(&rtp->lastrxformat) / 1000) : 8);
03198 
03199    rtp->dtmf_timeout = 0;
03200 
03201    return f;
03202 }
03203 
03204 static struct ast_frame *process_cn_rfc3389(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct ast_sockaddr *addr, int payloadtype, int mark)
03205 {
03206    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
03207 
03208    /* Convert comfort noise into audio with various codecs.  Unfortunately this doesn't
03209       totally help us out becuase we don't have an engine to keep it going and we are not
03210       guaranteed to have it every 20ms or anything */
03211    if (rtpdebug)
03212       ast_debug(0, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", (int) rtp->lastrxformat.id, len);
03213 
03214    if (ast_test_flag(rtp, FLAG_3389_WARNING)) {
03215       struct ast_sockaddr remote_address = { {0,} };
03216 
03217       ast_rtp_instance_get_remote_address(instance, &remote_address);
03218 
03219       ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client address: %s\n",
03220          ast_sockaddr_stringify(&remote_address));
03221       ast_set_flag(rtp, FLAG_3389_WARNING);
03222    }
03223 
03224    /* Must have at least one byte */
03225    if (!len)
03226       return NULL;
03227    if (len < 24) {
03228       rtp->f.data.ptr = rtp->rawdata + AST_FRIENDLY_OFFSET;
03229       rtp->f.datalen = len - 1;
03230       rtp->f.offset = AST_FRIENDLY_OFFSET;
03231       memcpy(rtp->f.data.ptr, data + 1, len - 1);
03232    } else {
03233       rtp->f.data.ptr = NULL;
03234       rtp->f.offset = 0;
03235       rtp->f.datalen = 0;
03236    }
03237    rtp->f.frametype = AST_FRAME_CNG;
03238    rtp->f.subclass.integer = data[0] & 0x7f;
03239    rtp->f.samples = 0;
03240    rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
03241 
03242    return &rtp->f;
03243 }
03244 
03245 static struct ast_frame *ast_rtcp_read(struct ast_rtp_instance *instance)
03246 {
03247    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
03248    struct ast_sockaddr addr;
03249    unsigned char rtcpdata[8192 + AST_FRIENDLY_OFFSET];
03250    unsigned int *rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
03251    int res, packetwords, position = 0;
03252    struct ast_frame *f = &ast_null_frame;
03253 
03254    /* Read in RTCP data from the socket */
03255    if ((res = rtcp_recvfrom(instance, rtcpdata + AST_FRIENDLY_OFFSET,
03256             sizeof(rtcpdata) - AST_FRIENDLY_OFFSET,
03257             0, &addr)) < 0) {
03258       ast_assert(errno != EBADF);
03259       if (errno != EAGAIN) {
03260          ast_log(LOG_WARNING, "RTCP Read error: %s.  Hanging up.\n",
03261             (errno) ? strerror(errno) : "Unspecified");
03262          return NULL;
03263       }
03264       return &ast_null_frame;
03265    }
03266 
03267    /* If this was handled by the ICE session don't do anything further */
03268    if (!res) {
03269       return &ast_null_frame;
03270    }
03271 
03272    if (!*(rtcpdata + AST_FRIENDLY_OFFSET)) {
03273       struct sockaddr_in addr_tmp;
03274       struct ast_sockaddr addr_v4;
03275 
03276       if (ast_sockaddr_is_ipv4(&addr)) {
03277          ast_sockaddr_to_sin(&addr, &addr_tmp);
03278       } else if (ast_sockaddr_ipv4_mapped(&addr, &addr_v4)) {
03279          ast_debug(1, "Using IPv6 mapped address %s for STUN\n",
03280               ast_sockaddr_stringify(&addr));
03281          ast_sockaddr_to_sin(&addr_v4, &addr_tmp);
03282       } else {
03283          ast_debug(1, "Cannot do STUN for non IPv4 address %s\n",
03284               ast_sockaddr_stringify(&addr));
03285          return &ast_null_frame;
03286       }
03287       if ((ast_stun_handle_packet(rtp->rtcp->s, &addr_tmp, rtcpdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == AST_STUN_ACCEPT)) {
03288          ast_sockaddr_from_sin(&addr, &addr_tmp);
03289          ast_sockaddr_copy(&rtp->rtcp->them, &addr);
03290       }
03291       return &ast_null_frame;
03292    }
03293 
03294    packetwords = res / 4;
03295 
03296    if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT)) {
03297       /* Send to whoever sent to us */
03298       if (ast_sockaddr_cmp(&rtp->rtcp->them, &addr)) {
03299          ast_sockaddr_copy(&rtp->rtcp->them, &addr);
03300          if (rtpdebug)
03301             ast_debug(0, "RTCP NAT: Got RTCP from other end. Now sending to address %s\n",
03302                  ast_sockaddr_stringify(&rtp->rtcp->them));
03303       }
03304    }
03305 
03306    ast_debug(1, "Got RTCP report of %d bytes\n", res);
03307 
03308    while (position < packetwords) {
03309       int i, pt, rc;
03310       unsigned int length, dlsr, lsr, msw, lsw, comp;
03311       struct timeval now;
03312       double rttsec, reported_jitter, reported_normdev_jitter_current, normdevrtt_current, reported_lost, reported_normdev_lost_current;
03313       uint64_t rtt = 0;
03314 
03315       i = position;
03316       length = ntohl(rtcpheader[i]);
03317       pt = (length & 0xff0000) >> 16;
03318       rc = (length & 0x1f000000) >> 24;
03319       length &= 0xffff;
03320 
03321       if ((i + length) > packetwords) {
03322          if (rtpdebug)
03323             ast_debug(1, "RTCP Read too short\n");
03324          return &ast_null_frame;
03325       }
03326 
03327       if (rtcp_debug_test_addr(&addr)) {
03328          ast_verbose("\n\nGot RTCP from %s\n",
03329                 ast_sockaddr_stringify(&addr));
03330          ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
03331          ast_verbose("Reception reports: %d\n", rc);
03332          ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
03333       }
03334 
03335       i += 2; /* Advance past header and ssrc */
03336       if (rc == 0 && pt == RTCP_PT_RR) {      /* We're receiving a receiver report with no reports, which is ok */
03337          position += (length + 1);
03338          continue;
03339       }
03340 
03341       switch (pt) {
03342       case RTCP_PT_SR:
03343          gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
03344          rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
03345          rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
03346          rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16); /* Going to LSR in RR*/
03347 
03348          if (rtcp_debug_test_addr(&addr)) {
03349             ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
03350             ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
03351             ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
03352          }
03353          i += 5;
03354          if (rc < 1)
03355             break;
03356          /* Intentional fall through */
03357       case RTCP_PT_RR:
03358          /* Don't handle multiple reception reports (rc > 1) yet */
03359          /* Calculate RTT per RFC */
03360          gettimeofday(&now, NULL);
03361          timeval2ntp(now, &msw, &lsw);
03362          if (ntohl(rtcpheader[i + 4]) && ntohl(rtcpheader[i + 5])) { /* We must have the LSR && DLSR */
03363             comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
03364             lsr = ntohl(rtcpheader[i + 4]);
03365             dlsr = ntohl(rtcpheader[i + 5]);
03366             rtt = comp - lsr - dlsr;
03367 
03368             /* Convert end to end delay to usec (keeping the calculation in 64bit space)
03369                sess->ee_delay = (eedelay * 1000) / 65536; */
03370             if (rtt < 4294) {
03371                rtt = (rtt * 1000000) >> 16;
03372             } else {
03373                rtt = (rtt * 1000) >> 16;
03374                rtt *= 1000;
03375             }
03376             rtt = rtt / 1000.;
03377             rttsec = rtt / 1000.;
03378             rtp->rtcp->rtt = rttsec;
03379 
03380             if (comp - dlsr >= lsr) {
03381                rtp->rtcp->accumulated_transit += rttsec;
03382 
03383                if (rtp->rtcp->rtt_count == 0)
03384                   rtp->rtcp->minrtt = rttsec;
03385 
03386                if (rtp->rtcp->maxrtt<rttsec)
03387                   rtp->rtcp->maxrtt = rttsec;
03388                if (rtp->rtcp->minrtt>rttsec)
03389                   rtp->rtcp->minrtt = rttsec;
03390 
03391                normdevrtt_current = normdev_compute(rtp->rtcp->normdevrtt, rttsec, rtp->rtcp->rtt_count);
03392 
03393                rtp->rtcp->stdevrtt = stddev_compute(rtp->rtcp->stdevrtt, rttsec, rtp->rtcp->normdevrtt, normdevrtt_current, rtp->rtcp->rtt_count);
03394 
03395                rtp->rtcp->normdevrtt = normdevrtt_current;
03396 
03397                rtp->rtcp->rtt_count++;
03398             } else if (rtcp_debug_test_addr(&addr)) {
03399                ast_verbose("Internal RTCP NTP clock skew detected: "
03400                         "lsr=%u, now=%u, dlsr=%u (%d:%03dms), "
03401                       "diff=%d\n",
03402                       lsr, comp, dlsr, dlsr / 65536,
03403                       (dlsr % 65536) * 1000 / 65536,
03404                       dlsr - (comp - lsr));
03405             }
03406          }
03407 
03408          rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
03409          reported_jitter = (double) rtp->rtcp->reported_jitter;
03410 
03411          if (rtp->rtcp->reported_jitter_count == 0)
03412             rtp->rtcp->reported_minjitter = reported_jitter;
03413 
03414          if (reported_jitter < rtp->rtcp->reported_minjitter)
03415             rtp->rtcp->reported_minjitter = reported_jitter;
03416 
03417          if (reported_jitter > rtp->rtcp->reported_maxjitter)
03418             rtp->rtcp->reported_maxjitter = reported_jitter;
03419 
03420          reported_normdev_jitter_current = normdev_compute(rtp->rtcp->reported_normdev_jitter, reported_jitter, rtp->rtcp->reported_jitter_count);
03421 
03422          rtp->rtcp->reported_stdev_jitter = stddev_compute(rtp->rtcp->reported_stdev_jitter, reported_jitter, rtp->rtcp->reported_normdev_jitter, reported_normdev_jitter_current, rtp->rtcp->reported_jitter_count);
03423 
03424          rtp->rtcp->reported_normdev_jitter = reported_normdev_jitter_current;
03425 
03426          rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
03427 
03428          reported_lost = (double) rtp->rtcp->reported_lost;
03429 
03430          /* using same counter as for jitter */
03431          if (rtp->rtcp->reported_jitter_count == 0)
03432             rtp->rtcp->reported_minlost = reported_lost;
03433 
03434          if (reported_lost < rtp->rtcp->reported_minlost)
03435             rtp->rtcp->reported_minlost = reported_lost;
03436 
03437          if (reported_lost > rtp->rtcp->reported_maxlost)
03438             rtp->rtcp->reported_maxlost = reported_lost;
03439          reported_normdev_lost_current = normdev_compute(rtp->rtcp->reported_normdev_lost, reported_lost, rtp->rtcp->reported_jitter_count);
03440 
03441          rtp->rtcp->reported_stdev_lost = stddev_compute(rtp->rtcp->reported_stdev_lost, reported_lost, rtp->rtcp->reported_normdev_lost, reported_normdev_lost_current, rtp->rtcp->reported_jitter_count);
03442 
03443          rtp->rtcp->reported_normdev_lost = reported_normdev_lost_current;
03444 
03445          rtp->rtcp->reported_jitter_count++;
03446 
03447          if (rtcp_debug_test_addr(&addr)) {
03448             ast_verbose("  Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
03449             ast_verbose("  Packets lost so far: %d\n", rtp->rtcp->reported_lost);
03450             ast_verbose("  Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
03451             ast_verbose("  Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2])) >> 16);
03452             ast_verbose("  Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
03453             ast_verbose("  Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
03454             ast_verbose("  DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
03455             if (rtt)
03456                ast_verbose("  RTT: %lu(sec)\n", (unsigned long) rtt);
03457          }
03458          if (rtt) {
03459             manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s\r\n"
03460                             "PT: %d(%s)\r\n"
03461                             "ReceptionReports: %d\r\n"
03462                             "SenderSSRC: %u\r\n"
03463                             "FractionLost: %ld\r\n"
03464                             "PacketsLost: %d\r\n"
03465                             "HighestSequence: %ld\r\n"
03466                             "SequenceNumberCycles: %ld\r\n"
03467                             "IAJitter: %u\r\n"
03468                             "LastSR: %lu.%010lu\r\n"
03469                             "DLSR: %4.4f(sec)\r\n"
03470                      "RTT: %llu(sec)\r\n",
03471                      ast_sockaddr_stringify(&addr),
03472                      pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
03473                      rc,
03474                      rtcpheader[i + 1],
03475                      (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
03476                      rtp->rtcp->reported_lost,
03477                      (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
03478                      (long) (ntohl(rtcpheader[i + 2])) >> 16,
03479                      rtp->rtcp->reported_jitter,
03480                      (unsigned long) ntohl(rtcpheader[i + 4]) >> 16, ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
03481                      ntohl(rtcpheader[i + 5])/65536.0,
03482                      (unsigned long long)rtt);
03483          } else {
03484             manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s\r\n"
03485                             "PT: %d(%s)\r\n"
03486                             "ReceptionReports: %d\r\n"
03487                             "SenderSSRC: %u\r\n"
03488                             "FractionLost: %ld\r\n"
03489                             "PacketsLost: %d\r\n"
03490                             "HighestSequence: %ld\r\n"
03491                             "SequenceNumberCycles: %ld\r\n"
03492                             "IAJitter: %u\r\n"
03493                             "LastSR: %lu.%010lu\r\n"
03494                      "DLSR: %4.4f(sec)\r\n",
03495                      ast_sockaddr_stringify(&addr),
03496                      pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
03497                      rc,
03498                      rtcpheader[i + 1],
03499                      (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
03500                      rtp->rtcp->reported_lost,
03501                      (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
03502                      (long) (ntohl(rtcpheader[i + 2])) >> 16,
03503                      rtp->rtcp->reported_jitter,
03504                      (unsigned long) ntohl(rtcpheader[i + 4]) >> 16,
03505                      ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
03506                      ntohl(rtcpheader[i + 5])/65536.0);
03507          }
03508          break;
03509       case RTCP_PT_FUR:
03510          if (rtcp_debug_test_addr(&addr))
03511             ast_verbose("Received an RTCP Fast Update Request\n");
03512          rtp->f.frametype = AST_FRAME_CONTROL;
03513          rtp->f.subclass.integer = AST_CONTROL_VIDUPDATE;
03514          rtp->f.datalen = 0;
03515          rtp->f.samples = 0;
03516          rtp->f.mallocd = 0;
03517          rtp->f.src = "RTP";
03518          f = &rtp->f;
03519          break;
03520       case RTCP_PT_SDES:
03521          if (rtcp_debug_test_addr(&addr))
03522             ast_verbose("Received an SDES from %s\n",
03523                    ast_sockaddr_stringify(&rtp->rtcp->them));
03524          break;
03525       case RTCP_PT_BYE:
03526          if (rtcp_debug_test_addr(&addr))
03527             ast_verbose("Received a BYE from %s\n",
03528                    ast_sockaddr_stringify(&rtp->rtcp->them));
03529          break;
03530       default:
03531          ast_debug(1, "Unknown RTCP packet (pt=%d) received from %s\n",
03532               pt, ast_sockaddr_stringify(&rtp->rtcp->them));
03533          break;
03534       }
03535       position += (length + 1);
03536    }
03537 
03538    rtp->rtcp->rtcp_info = 1;
03539 
03540    return f;
03541 }
03542 
03543 static int bridge_p2p_rtp_write(struct ast_rtp_instance *instance, unsigned int *rtpheader, int len, int hdrlen)
03544 {
03545    struct ast_rtp_instance *instance1 = ast_rtp_instance_get_bridged(instance);
03546    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance), *bridged = ast_rtp_instance_get_data(instance1);
03547    int res = 0, payload = 0, bridged_payload = 0, mark;
03548    struct ast_rtp_payload_type payload_type;
03549    int reconstruct = ntohl(rtpheader[0]);
03550    struct ast_sockaddr remote_address = { {0,} };
03551    int ice;
03552 
03553    /* Get fields from packet */
03554    payload = (reconstruct & 0x7f0000) >> 16;
03555    mark = (((reconstruct & 0x800000) >> 23) != 0);
03556 
03557    /* Check what the payload value should be */
03558    payload_type = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(instance), payload);
03559 
03560    /* Otherwise adjust bridged payload to match */
03561    bridged_payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance1), payload_type.asterisk_format, &payload_type.format, payload_type.rtp_code);
03562 
03563    /* If no codec could be matched between instance and instance1, then somehow things were made incompatible while we were still bridged.  Bail. */
03564    if (bridged_payload < 0) {
03565       return -1;
03566    }
03567 
03568    /* If the payload coming in is not one of the negotiated ones then send it to the core, this will cause formats to change and the bridge to break */
03569    if (ast_rtp_codecs_find_payload_code(ast_rtp_instance_get_codecs(instance1), bridged_payload) == -1) {
03570       ast_debug(1, "Unsupported payload type received \n");
03571       return -1;
03572    }
03573 
03574    /* If the marker bit has been explicitly set turn it on */
03575    if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
03576       mark = 1;
03577       ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
03578    }
03579 
03580    /* Reconstruct part of the packet */
03581    reconstruct &= 0xFF80FFFF;
03582    reconstruct |= (bridged_payload << 16);
03583    reconstruct |= (mark << 23);
03584    rtpheader[0] = htonl(reconstruct);
03585 
03586    ast_rtp_instance_get_remote_address(instance1, &remote_address);
03587 
03588    if (ast_sockaddr_isnull(&remote_address)) {
03589       ast_debug(1, "Remote address is null, most likely RTP has been stopped\n");
03590       return 0;
03591    }
03592 
03593    /* Send the packet back out */
03594    res = rtp_sendto(instance1, (void *)rtpheader, len, 0, &remote_address, &ice);
03595    if (res < 0) {
03596       if (!ast_rtp_instance_get_prop(instance1, AST_RTP_PROPERTY_NAT) || (ast_rtp_instance_get_prop(instance1, AST_RTP_PROPERTY_NAT) && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
03597          ast_log(LOG_WARNING,
03598             "RTP Transmission error of packet to %s: %s\n",
03599             ast_sockaddr_stringify(&remote_address),
03600             strerror(errno));
03601       } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
03602          if (option_debug || rtpdebug)
03603             ast_log(LOG_WARNING,
03604                "RTP NAT: Can't write RTP to private "
03605                "address %s, waiting for other end to "
03606                "send audio...\n",
03607                ast_sockaddr_stringify(&remote_address));
03608          ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
03609       }
03610       return 0;
03611    }
03612 
03613 #ifdef USE_PJPROJECT
03614    update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
03615 #endif
03616 
03617    if (rtp_debug_test_addr(&remote_address)) {
03618       ast_verbose("Sent RTP P2P packet to %s%s (type %-2.2d, len %-6.6u)\n",
03619              ast_sockaddr_stringify(&remote_address),
03620              ice ? " (via ICE)" : "",
03621              bridged_payload, len - hdrlen);
03622    }
03623 
03624    return 0;
03625 }
03626 
03627 static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp)
03628 {
03629    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
03630    struct ast_sockaddr addr;
03631    int res, hdrlen = 12, version, payloadtype, padding, mark, ext, cc, prev_seqno;
03632    unsigned int *rtpheader = (unsigned int*)(rtp->rawdata + AST_FRIENDLY_OFFSET), seqno, ssrc, timestamp;
03633    struct ast_rtp_payload_type payload;
03634    struct ast_sockaddr remote_address = { {0,} };
03635    struct frame_list frames;
03636 
03637    /* If this is actually RTCP let's hop on over and handle it */
03638    if (rtcp) {
03639       if (rtp->rtcp) {
03640          return ast_rtcp_read(instance);
03641       }
03642       return &ast_null_frame;
03643    }
03644 
03645    /* If we are currently sending DTMF to the remote party send a continuation packet */
03646    if (rtp->sending_digit) {
03647       ast_rtp_dtmf_continuation(instance);
03648    }
03649 
03650    /* Actually read in the data from the socket */
03651    if ((res = rtp_recvfrom(instance, rtp->rawdata + AST_FRIENDLY_OFFSET,
03652             sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0,
03653             &addr)) < 0) {
03654       ast_assert(errno != EBADF);
03655       if (errno != EAGAIN) {
03656          ast_log(LOG_WARNING, "RTP Read error: %s.  Hanging up.\n",
03657             (errno) ? strerror(errno) : "Unspecified");
03658          return NULL;
03659       }
03660       return &ast_null_frame;
03661    }
03662 
03663    /* If this was handled by the ICE session don't do anything */
03664    if (!res) {
03665       return &ast_null_frame;
03666    }
03667 
03668    /* Make sure the data that was read in is actually enough to make up an RTP packet */
03669    if (res < hdrlen) {
03670       ast_log(LOG_WARNING, "RTP Read too short\n");
03671       return &ast_null_frame;
03672    }
03673 
03674    /* Get fields and verify this is an RTP packet */
03675    seqno = ntohl(rtpheader[0]);
03676 
03677    ast_rtp_instance_get_remote_address(instance, &remote_address);
03678 
03679    if (!(version = (seqno & 0xC0000000) >> 30)) {
03680       struct sockaddr_in addr_tmp;
03681       struct ast_sockaddr addr_v4;
03682       if (ast_sockaddr_is_ipv4(&addr)) {
03683          ast_sockaddr_to_sin(&addr, &addr_tmp);
03684       } else if (ast_sockaddr_ipv4_mapped(&addr, &addr_v4)) {
03685          ast_debug(1, "Using IPv6 mapped address %s for STUN\n",
03686               ast_sockaddr_stringify(&addr));
03687          ast_sockaddr_to_sin(&addr_v4, &addr_tmp);
03688       } else {
03689          ast_debug(1, "Cannot do STUN for non IPv4 address %s\n",
03690               ast_sockaddr_stringify(&addr));
03691          return &ast_null_frame;
03692       }
03693       if ((ast_stun_handle_packet(rtp->s, &addr_tmp, rtp->rawdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == AST_STUN_ACCEPT) &&
03694           ast_sockaddr_isnull(&remote_address)) {
03695          ast_sockaddr_from_sin(&addr, &addr_tmp);
03696          ast_rtp_instance_set_remote_address(instance, &addr);
03697       }
03698       return &ast_null_frame;
03699    }
03700 
03701    /* If strict RTP protection is enabled see if we need to learn the remote address or if we need to drop the packet */
03702    if (rtp->strict_rtp_state == STRICT_RTP_LEARN) {
03703       ast_debug(1, "%p -- Probation learning mode pass with source address %s\n", rtp, ast_sockaddr_stringify(&addr));
03704       /* For now, we always copy the address. */
03705       ast_sockaddr_copy(&rtp->strict_rtp_address, &addr);
03706 
03707       /* Send the rtp and the seqno from header to rtp_learning_rtp_seq_update to see whether we can exit or not*/
03708       if (rtp_learning_rtp_seq_update(&rtp->rtp_source_learn, seqno)) {
03709          ast_debug(1, "%p -- Probation at seq %d with %d to go; discarding frame\n",
03710             rtp, rtp->rtp_source_learn.max_seq, rtp->rtp_source_learn.packets);
03711          return &ast_null_frame;
03712       }
03713 
03714       ast_verb(4, "%p -- Probation passed - setting RTP source address to %s\n", rtp, ast_sockaddr_stringify(&addr));
03715       rtp->strict_rtp_state = STRICT_RTP_CLOSED;
03716    }
03717    if (rtp->strict_rtp_state == STRICT_RTP_CLOSED) {
03718       if (!ast_sockaddr_cmp(&rtp->strict_rtp_address, &addr)) {
03719          /* Always reset the alternate learning source */
03720          rtp_learning_seq_init(&rtp->alt_source_learn, seqno);
03721       } else {
03722          /* Hmm, not the strict address. Perhaps we're getting audio from the alternate? */
03723          if (!ast_sockaddr_cmp(&rtp->alt_rtp_address, &addr)) {
03724             /* ooh, we did! You're now the new expected address, son! */
03725             ast_sockaddr_copy(&rtp->strict_rtp_address,
03726                     &addr);
03727          } else {
03728             /* Start trying to learn from the new address. If we pass a probationary period with
03729              * it, that means we've stopped getting RTP from the original source and we should
03730              * switch to it.
03731              */
03732             if (rtp_learning_rtp_seq_update(&rtp->alt_source_learn, seqno)) {
03733                ast_debug(1, "%p -- Received RTP packet from %s, dropping due to strict RTP protection. Will switch to it in %d packets\n",
03734                      rtp, ast_sockaddr_stringify(&addr), rtp->alt_source_learn.packets);
03735                return &ast_null_frame;
03736             }
03737             ast_verb(4, "%p -- Switching RTP source address to %s\n", rtp, ast_sockaddr_stringify(&addr));
03738             ast_sockaddr_copy(&rtp->strict_rtp_address, &addr);
03739          }
03740       }
03741    }
03742 
03743    /* If symmetric RTP is enabled see if the remote side is not what we expected and change where we are sending audio */
03744    if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT)) {
03745       if (ast_sockaddr_cmp(&remote_address, &addr)) {
03746          ast_rtp_instance_set_remote_address(instance, &addr);
03747          ast_sockaddr_copy(&remote_address, &addr);
03748          if (rtp->rtcp) {
03749             ast_sockaddr_copy(&rtp->rtcp->them, &addr);
03750             ast_sockaddr_set_port(&rtp->rtcp->them, ast_sockaddr_port(&addr) + 1);
03751          }
03752          rtp->rxseqno = 0;
03753          ast_set_flag(rtp, FLAG_NAT_ACTIVE);
03754          if (rtpdebug)
03755             ast_debug(0, "RTP NAT: Got audio from other end. Now sending to address %s\n",
03756                  ast_sockaddr_stringify(&remote_address));
03757       }
03758    }
03759 
03760    /* If we are directly bridged to another instance send the audio directly out */
03761    if (ast_rtp_instance_get_bridged(instance) && !bridge_p2p_rtp_write(instance, rtpheader, res, hdrlen)) {
03762       return &ast_null_frame;
03763    }
03764 
03765    /* If the version is not what we expected by this point then just drop the packet */
03766    if (version != 2) {
03767       return &ast_null_frame;
03768    }
03769 
03770    /* Pull out the various other fields we will need */
03771    payloadtype = (seqno & 0x7f0000) >> 16;
03772    padding = seqno & (1 << 29);
03773    mark = seqno & (1 << 23);
03774    ext = seqno & (1 << 28);
03775    cc = (seqno & 0xF000000) >> 24;
03776    seqno &= 0xffff;
03777    timestamp = ntohl(rtpheader[1]);
03778    ssrc = ntohl(rtpheader[2]);
03779 
03780    AST_LIST_HEAD_INIT_NOLOCK(&frames);
03781    /* Force a marker bit and change SSRC if the SSRC changes */
03782    if (rtp->rxssrc && rtp->rxssrc != ssrc) {
03783       struct ast_frame *f, srcupdate = {
03784          AST_FRAME_CONTROL,
03785          .subclass.integer = AST_CONTROL_SRCCHANGE,
03786       };
03787 
03788       if (!mark) {
03789          if (rtpdebug) {
03790             ast_debug(1, "Forcing Marker bit, because SSRC has changed\n");
03791          }
03792          mark = 1;
03793       }
03794 
03795       f = ast_frisolate(&srcupdate);
03796       AST_LIST_INSERT_TAIL(&frames, f, frame_list);
03797 
03798       rtp->seedrxseqno = 0;
03799       rtp->rxcount = 0;
03800       rtp->cycles = 0;
03801       rtp->lastrxseqno = 0;
03802       rtp->last_seqno = 0;
03803       rtp->last_end_timestamp = 0;
03804       if (rtp->rtcp) {
03805          rtp->rtcp->expected_prior = 0;
03806          rtp->rtcp->received_prior = 0;
03807       }
03808    }
03809 
03810    rtp->rxssrc = ssrc;
03811 
03812    /* Remove any padding bytes that may be present */
03813    if (padding) {
03814       res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
03815    }
03816 
03817    /* Skip over any CSRC fields */
03818    if (cc) {
03819       hdrlen += cc * 4;
03820    }
03821 
03822    /* Look for any RTP extensions, currently we do not support any */
03823    if (ext) {
03824       hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
03825       hdrlen += 4;
03826       if (option_debug) {
03827          int profile;
03828          profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
03829          if (profile == 0x505a)
03830             ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
03831          else
03832             ast_debug(1, "Found unknown RTP Extensions %x\n", profile);
03833       }
03834    }
03835 
03836    /* Make sure after we potentially mucked with the header length that it is once again valid */
03837    if (res < hdrlen) {
03838       ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d\n", res, hdrlen);
03839       return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
03840    }
03841 
03842    rtp->rxcount++;
03843    if (rtp->rxcount == 1) {
03844       rtp->seedrxseqno = seqno;
03845    }
03846 
03847    /* Do not schedule RR if RTCP isn't run */
03848    if (rtp->rtcp && !ast_sockaddr_isnull(&rtp->rtcp->them) && rtp->rtcp->schedid < 1) {
03849       /* Schedule transmission of Receiver Report */
03850       ao2_ref(instance, +1);
03851       rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, instance);
03852       if (rtp->rtcp->schedid < 0) {
03853          ao2_ref(instance, -1);
03854          ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
03855       }
03856    }
03857    if ((int)rtp->lastrxseqno - (int)seqno  > 100) /* if so it would indicate that the sender cycled; allow for misordering */
03858       rtp->cycles += RTP_SEQ_MOD;
03859 
03860    prev_seqno = rtp->lastrxseqno;
03861    rtp->lastrxseqno = seqno;
03862 
03863    if (!rtp->themssrc) {
03864       rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
03865    }
03866 
03867    if (rtp_debug_test_addr(&addr)) {
03868       ast_verbose("Got  RTP packet from    %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
03869              ast_sockaddr_stringify(&addr),
03870              payloadtype, seqno, timestamp,res - hdrlen);
03871    }
03872 
03873    payload = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(instance), payloadtype);
03874 
03875    /* If the payload is not actually an Asterisk one but a special one pass it off to the respective handler */
03876    if (!payload.asterisk_format) {
03877       struct ast_frame *f = NULL;
03878       if (payload.rtp_code == AST_RTP_DTMF) {
03879          /* process_dtmf_rfc2833 may need to return multiple frames. We do this
03880           * by passing the pointer to the frame list to it so that the method
03881           * can append frames to the list as needed.
03882           */
03883          process_dtmf_rfc2833(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark, &frames);
03884       } else if (payload.rtp_code == AST_RTP_CISCO_DTMF) {
03885          f = process_dtmf_cisco(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark);
03886       } else if (payload.rtp_code == AST_RTP_CN) {
03887          f = process_cn_rfc3389(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark);
03888       } else {
03889          ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n",
03890             payloadtype,
03891             ast_sockaddr_stringify(&remote_address));
03892       }
03893 
03894       if (f) {
03895          AST_LIST_INSERT_TAIL(&frames, f, frame_list);
03896       }
03897       /* Even if no frame was returned by one of the above methods,
03898        * we may have a frame to return in our frame list
03899        */
03900       if (!AST_LIST_EMPTY(&frames)) {
03901          return AST_LIST_FIRST(&frames);
03902       }
03903       return &ast_null_frame;
03904    }
03905 
03906    ast_format_copy(&rtp->lastrxformat, &payload.format);
03907    ast_format_copy(&rtp->f.subclass.format, &payload.format);
03908    rtp->f.frametype = (AST_FORMAT_GET_TYPE(rtp->f.subclass.format.id) == AST_FORMAT_TYPE_AUDIO) ? AST_FRAME_VOICE : (AST_FORMAT_GET_TYPE(rtp->f.subclass.format.id) == AST_FORMAT_TYPE_VIDEO) ? AST_FRAME_VIDEO : AST_FRAME_TEXT;
03909 
03910    rtp->rxseqno = seqno;
03911 
03912    if (rtp->dtmf_timeout && rtp->dtmf_timeout < timestamp) {
03913       rtp->dtmf_timeout = 0;
03914 
03915       if (rtp->resp) {
03916          struct ast_frame *f;
03917          f = create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0);
03918          f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(&f->subclass.format)), ast_tv(0, 0));
03919          rtp->resp = 0;
03920          rtp->dtmf_timeout = rtp->dtmf_duration = 0;
03921          AST_LIST_INSERT_TAIL(&frames, f, frame_list);
03922          return AST_LIST_FIRST(&frames);
03923       }
03924    }
03925 
03926    rtp->lastrxts = timestamp;
03927 
03928    rtp->f.src = "RTP";
03929    rtp->f.mallocd = 0;
03930    rtp->f.datalen = res - hdrlen;
03931    rtp->f.data.ptr = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
03932    rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
03933    rtp->f.seqno = seqno;
03934 
03935    if (rtp->f.subclass.format.id == AST_FORMAT_T140 && (int)seqno - (prev_seqno+1) > 0 && (int)seqno - (prev_seqno+1) < 10) {
03936       unsigned char *data = rtp->f.data.ptr;
03937 
03938       memmove(rtp->f.data.ptr+3, rtp->f.data.ptr, rtp->f.datalen);
03939       rtp->f.datalen +=3;
03940       *data++ = 0xEF;
03941       *data++ = 0xBF;
03942       *data = 0xBD;
03943    }
03944 
03945    if (rtp->f.subclass.format.id == AST_FORMAT_T140RED) {
03946       unsigned char *data = rtp->f.data.ptr;
03947       unsigned char *header_end;
03948       int num_generations;
03949       int header_length;
03950       int len;
03951       int diff =(int)seqno - (prev_seqno+1); /* if diff = 0, no drop*/
03952       int x;
03953 
03954       ast_format_set(&rtp->f.subclass.format, AST_FORMAT_T140, 0);
03955       header_end = memchr(data, ((*data) & 0x7f), rtp->f.datalen);
03956       if (header_end == NULL) {
03957          return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
03958       }
03959       header_end++;
03960 
03961       header_length = header_end - data;
03962       num_generations = header_length / 4;
03963       len = header_length;
03964 
03965       if (!diff) {
03966          for (x = 0; x < num_generations; x++)
03967             len += data[x * 4 + 3];
03968 
03969          if (!(rtp->f.datalen - len))
03970             return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
03971 
03972          rtp->f.data.ptr += len;
03973          rtp->f.datalen -= len;
03974       } else if (diff > num_generations && diff < 10) {
03975          len -= 3;
03976          rtp->f.data.ptr += len;
03977          rtp->f.datalen -= len;
03978 
03979          data = rtp->f.data.ptr;
03980          *data++ = 0xEF;
03981          *data++ = 0xBF;
03982          *data = 0xBD;
03983       } else {
03984          for ( x = 0; x < num_generations - diff; x++)
03985             len += data[x * 4 + 3];
03986 
03987          rtp->f.data.ptr += len;
03988          rtp->f.datalen -= len;
03989       }
03990    }
03991 
03992    if (AST_FORMAT_GET_TYPE(rtp->f.subclass.format.id) == AST_FORMAT_TYPE_AUDIO) {
03993       rtp->f.samples = ast_codec_get_samples(&rtp->f);
03994       if (ast_format_is_slinear(&rtp->f.subclass.format)) {
03995          ast_frame_byteswap_be(&rtp->f);
03996       }
03997       calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
03998       /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
03999       ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
04000       rtp->f.ts = timestamp / (rtp_get_rate(&rtp->f.subclass.format) / 1000);
04001       rtp->f.len = rtp->f.samples / ((ast_format_rate(&rtp->f.subclass.format) / 1000));
04002    } else if (AST_FORMAT_GET_TYPE(rtp->f.subclass.format.id) == AST_FORMAT_TYPE_VIDEO) {
04003       /* Video -- samples is # of samples vs. 90000 */
04004       if (!rtp->lastividtimestamp)
04005          rtp->lastividtimestamp = timestamp;
04006       rtp->f.samples = timestamp - rtp->lastividtimestamp;
04007       rtp->lastividtimestamp = timestamp;
04008       rtp->f.delivery.tv_sec = 0;
04009       rtp->f.delivery.tv_usec = 0;
04010       /* Pass the RTP marker bit as bit */
04011       if (mark) {
04012          ast_format_set_video_mark(&rtp->f.subclass.format);
04013       }
04014    } else {
04015       /* TEXT -- samples is # of samples vs. 1000 */
04016       if (!rtp->lastitexttimestamp)
04017          rtp->lastitexttimestamp = timestamp;
04018       rtp->f.samples = timestamp - rtp->lastitexttimestamp;
04019       rtp->lastitexttimestamp = timestamp;
04020       rtp->f.delivery.tv_sec = 0;
04021       rtp->f.delivery.tv_usec = 0;
04022    }
04023 
04024    AST_LIST_INSERT_TAIL(&frames, &rtp->f, frame_list);
04025    return AST_LIST_FIRST(&frames);
04026 }
04027 
04028 static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
04029 {
04030    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
04031 
04032    if (property == AST_RTP_PROPERTY_RTCP) {
04033       if (value) {
04034          if (rtp->rtcp) {
04035             ast_debug(1, "Ignoring duplicate RTCP property on RTP instance '%p'\n", instance);
04036             return;
04037          }
04038          /* Setup RTCP to be activated on the next RTP write */
04039          if (!(rtp->rtcp = ast_calloc(1, sizeof(*rtp->rtcp)))) {
04040             return;
04041          }
04042 
04043          /* Grab the IP address and port we are going to use */
04044          ast_rtp_instance_get_local_address(instance, &rtp->rtcp->us);
04045          ast_sockaddr_set_port(&rtp->rtcp->us,
04046                      ast_sockaddr_port(&rtp->rtcp->us) + 1);
04047 
04048          if ((rtp->rtcp->s =
04049               create_new_socket("RTCP",
04050                       ast_sockaddr_is_ipv4(&rtp->rtcp->us) ?
04051                       AF_INET :
04052                       ast_sockaddr_is_ipv6(&rtp->rtcp->us) ?
04053                       AF_INET6 : -1)) < 0) {
04054             ast_debug(1, "Failed to create a new socket for RTCP on instance '%p'\n", instance);
04055             ast_free(rtp->rtcp);
04056             rtp->rtcp = NULL;
04057             return;
04058          }
04059 
04060          /* Try to actually bind to the IP address and port we are going to use for RTCP, if this fails we have to bail out */
04061          if (ast_bind(rtp->rtcp->s, &rtp->rtcp->us)) {
04062             ast_debug(1, "Failed to setup RTCP on RTP instance '%p'\n", instance);
04063             close(rtp->rtcp->s);
04064             ast_free(rtp->rtcp);
04065             rtp->rtcp = NULL;
04066             return;
04067          }
04068 
04069          ast_debug(1, "Setup RTCP on RTP instance '%p'\n", instance);
04070          rtp->rtcp->schedid = -1;
04071 
04072 #ifdef USE_PJPROJECT
04073          if (rtp->ice) {
04074             rtp_add_candidates_to_ice(instance, rtp, &rtp->rtcp->us, ast_sockaddr_port(&rtp->rtcp->us), AST_RTP_ICE_COMPONENT_RTCP, TRANSPORT_SOCKET_RTCP,
04075                        &ast_rtp_turn_rtcp_sock_cb, &rtp->turn_rtcp);
04076          }
04077 #endif
04078 
04079          return;
04080       } else {
04081          if (rtp->rtcp) {
04082             if (rtp->rtcp->schedid > 0) {
04083                if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
04084                   /* Successfully cancelled scheduler entry. */
04085                   ao2_ref(instance, -1);
04086                } else {
04087                   /* Unable to cancel scheduler entry */
04088                   ast_debug(1, "Failed to tear down RTCP on RTP instance '%p'\n", instance);
04089                   return;
04090                }
04091                rtp->rtcp->schedid = -1;
04092             }
04093             close(rtp->rtcp->s);
04094             ast_free(rtp->rtcp);
04095             rtp->rtcp = NULL;
04096          }
04097          return;
04098       }
04099    }
04100 
04101    return;
04102 }
04103 
04104 static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp)
04105 {
04106    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
04107 
04108    return rtcp ? (rtp->rtcp ? rtp->rtcp->s : -1) : rtp->s;
04109 }
04110 
04111 static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr)
04112 {
04113    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
04114 
04115    if (rtp->rtcp) {
04116       ast_debug(1, "Setting RTCP address on RTP instance '%p'\n", instance);
04117       ast_sockaddr_copy(&rtp->rtcp->them, addr);
04118       if (!ast_sockaddr_isnull(addr)) {
04119          ast_sockaddr_set_port(&rtp->rtcp->them,
04120                      ast_sockaddr_port(addr) + 1);
04121       }
04122    }
04123 
04124    rtp->rxseqno = 0;
04125 
04126    if (strictrtp && rtp->strict_rtp_state != STRICT_RTP_OPEN) {
04127       rtp->strict_rtp_state = STRICT_RTP_LEARN;
04128       rtp_learning_seq_init(&rtp->rtp_source_learn, rtp->seqno);
04129    }
04130 
04131    return;
04132 }
04133 
04134 static void ast_rtp_alt_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr)
04135 {
04136    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
04137 
04138    /* No need to futz with rtp->rtcp here because ast_rtcp_read is already able to adjust if receiving
04139     * RTCP from an "unexpected" source
04140     */
04141    ast_sockaddr_copy(&rtp->alt_rtp_address, addr);
04142 
04143    return;
04144 }
04145 
04146 /*! \brief Write t140 redundacy frame
04147  * \param data primary data to be buffered
04148  */
04149 static int red_write(const void *data)
04150 {
04151    struct ast_rtp_instance *instance = (struct ast_rtp_instance*) data;
04152    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
04153 
04154    ast_rtp_write(instance, &rtp->red->t140);
04155 
04156    return 1;
04157 }
04158 
04159 static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
04160 {
04161    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
04162    int x;
04163 
04164    if (!(rtp->red = ast_calloc(1, sizeof(*rtp->red)))) {
04165       return -1;
04166    }
04167 
04168    rtp->red->t140.frametype = AST_FRAME_TEXT;
04169    ast_format_set(&rtp->red->t140.subclass.format, AST_FORMAT_T140RED, 0);
04170    rtp->red->t140.data.ptr = &rtp->red->buf_data;
04171 
04172    rtp->red->t140.ts = 0;
04173    rtp->red->t140red = rtp->red->t140;
04174    rtp->red->t140red.data.ptr = &rtp->red->t140red_data;
04175    rtp->red->t140red.datalen = 0;
04176    rtp->red->ti = buffer_time;
04177    rtp->red->num_gen = generations;
04178    rtp->red->hdrlen = generations * 4 + 1;
04179    rtp->red->prev_ts = 0;
04180 
04181    for (x = 0; x < generations; x++) {
04182       rtp->red->pt[x] = payloads[x];
04183       rtp->red->pt[x] |= 1 << 7; /* mark redundant generations pt */
04184       rtp->red->t140red_data[x*4] = rtp->red->pt[x];
04185    }
04186    rtp->red->t140red_data[x*4] = rtp->red->pt[x] = payloads[x]; /* primary pt */
04187    rtp->red->schedid = ast_sched_add(rtp->sched, generations, red_write, instance);
04188 
04189    rtp->red->t140.datalen = 0;
04190 
04191    return 0;
04192 }
04193 
04194 static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
04195 {
04196    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
04197 
04198    if (frame->datalen > -1) {
04199       struct rtp_red *red = rtp->red;
04200       memcpy(&red->buf_data[red->t140.datalen], frame->data.ptr, frame->datalen);
04201       red->t140.datalen += frame->datalen;
04202       red->t140.ts = frame->ts;
04203    }
04204 
04205    return 0;
04206 }
04207 
04208 static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1)
04209 {
04210    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance0);
04211 
04212    ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
04213 
04214    return 0;
04215 }
04216 
04217 static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
04218 {
04219    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
04220 
04221    if (!rtp->rtcp) {
04222       return -1;
04223    }
04224 
04225    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXCOUNT, -1, stats->txcount, rtp->txcount);
04226    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXCOUNT, -1, stats->rxcount, rtp->rxcount);
04227 
04228    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->txploss, rtp->rtcp->reported_lost);
04229    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->rxploss, rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
04230    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MAXRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_maxrxploss, rtp->rtcp->reported_maxlost);
04231    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MINRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_minrxploss, rtp->rtcp->reported_minlost);
04232    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_normdevrxploss, rtp->rtcp->reported_normdev_lost);
04233    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_STDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_stdevrxploss, rtp->rtcp->reported_stdev_lost);
04234    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MAXRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_maxrxploss, rtp->rtcp->maxrxlost);
04235    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MINRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_minrxploss, rtp->rtcp->minrxlost);
04236    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_normdevrxploss, rtp->rtcp->normdev_rxlost);
04237    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_STDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_stdevrxploss, rtp->rtcp->stdev_rxlost);
04238    AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_LOSS);
04239 
04240    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->txjitter, rtp->rxjitter);
04241    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->rxjitter, rtp->rtcp->reported_jitter / (unsigned int) 65536.0);
04242    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MAXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_maxjitter, rtp->rtcp->reported_maxjitter);
04243    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MINJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_minjitter, rtp->rtcp->reported_minjitter);
04244    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_normdevjitter, rtp->rtcp->reported_normdev_jitter);
04245    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_STDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_stdevjitter, rtp->rtcp->reported_stdev_jitter);
04246    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MAXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_maxjitter, rtp->rtcp->maxrxjitter);
04247    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MINJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_minjitter, rtp->rtcp->minrxjitter);
04248    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_normdevjitter, rtp->rtcp->normdev_rxjitter);
04249    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_STDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_stdevjitter, rtp->rtcp->stdev_rxjitter);
04250    AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_JITTER);
04251 
04252    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->rtt, rtp->rtcp->rtt);
04253    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_MAX_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->maxrtt, rtp->rtcp->maxrtt);
04254    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_MIN_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->minrtt, rtp->rtcp->minrtt);
04255    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_NORMDEVRTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->normdevrtt, rtp->rtcp->normdevrtt);
04256    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_STDEVRTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->stdevrtt, rtp->rtcp->stdevrtt);
04257    AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_RTT);
04258 
04259    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_SSRC, -1, stats->local_ssrc, rtp->ssrc);
04260    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_SSRC, -1, stats->remote_ssrc, rtp->themssrc);
04261 
04262    return 0;
04263 }
04264 
04265 static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1)
04266 {
04267    /* If both sides are not using the same method of DTMF transmission
04268     * (ie: one is RFC2833, other is INFO... then we can not do direct media.
04269     * --------------------------------------------------
04270     * | DTMF Mode |  HAS_DTMF  |  Accepts Begin Frames |
04271     * |-----------|------------|-----------------------|
04272     * | Inband    | False      | True                  |
04273     * | RFC2833   | True       | True                  |
04274     * | SIP INFO  | False      | False                 |
04275     * --------------------------------------------------
04276     */
04277    return (((ast_rtp_instance_get_prop(instance0, AST_RTP_PROPERTY_DTMF) != ast_rtp_instance_get_prop(instance1, AST_RTP_PROPERTY_DTMF)) ||
04278        (!ast_channel_tech(chan0)->send_digit_begin != !ast_channel_tech(chan1)->send_digit_begin)) ? 0 : 1);
04279 }
04280 
04281 static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username)
04282 {
04283    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
04284    struct sockaddr_in suggestion_tmp;
04285 
04286    ast_sockaddr_to_sin(suggestion, &suggestion_tmp);
04287    ast_stun_request(rtp->s, &suggestion_tmp, username, NULL);
04288    ast_sockaddr_from_sin(suggestion, &suggestion_tmp);
04289 }
04290 
04291 static void ast_rtp_stop(struct ast_rtp_instance *instance)
04292 {
04293    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
04294    struct ast_sockaddr addr = { {0,} };
04295 
04296 #ifdef HAVE_OPENSSL_SRTP
04297    AST_SCHED_DEL_UNREF(rtp->sched, rtp->rekeyid, ao2_ref(instance, -1));
04298 #endif
04299 
04300    if (rtp->rtcp && rtp->rtcp->schedid > 0) {
04301       if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
04302          /* successfully cancelled scheduler entry. */
04303          ao2_ref(instance, -1);
04304       }
04305       rtp->rtcp->schedid = -1;
04306    }
04307 
04308    if (rtp->red) {
04309       AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
04310       free(rtp->red);
04311       rtp->red = NULL;
04312    }
04313 
04314    ast_rtp_instance_set_remote_address(instance, &addr);
04315    if (rtp->rtcp) {
04316       ast_sockaddr_setnull(&rtp->rtcp->them);
04317    }
04318 
04319    ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
04320 }
04321 
04322 static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
04323 {
04324    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
04325 
04326    return ast_set_qos(rtp->s, tos, cos, desc);
04327 }
04328 
04329 /*! \brief generate comfort noice (CNG) */
04330 static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level)
04331 {
04332    unsigned int *rtpheader;
04333    int hdrlen = 12;
04334    int res, payload = 0;
04335    char data[256];
04336    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
04337    struct ast_sockaddr remote_address = { {0,} };
04338    int ice;
04339 
04340    ast_rtp_instance_get_remote_address(instance, &remote_address);
04341 
04342    if (ast_sockaddr_isnull(&remote_address)) {
04343       return -1;
04344    }
04345 
04346    payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, NULL, AST_RTP_CN);
04347 
04348    level = 127 - (level & 0x7f);
04349    
04350    rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
04351 
04352    /* Get a pointer to the header */
04353    rtpheader = (unsigned int *)data;
04354    rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
04355    rtpheader[1] = htonl(rtp->lastts);
04356    rtpheader[2] = htonl(rtp->ssrc); 
04357    data[12] = level;
04358 
04359    res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 1, 0, &remote_address, &ice);
04360 
04361    if (res < 0) {
04362       ast_log(LOG_ERROR, "RTP Comfort Noise Transmission error to %s: %s\n", ast_sockaddr_stringify(&remote_address), strerror(errno));
04363       return res;
04364    }
04365 
04366 #ifdef USE_PJPROJECT
04367    update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
04368 #endif
04369 
04370    if (rtp_debug_test_addr(&remote_address)) {
04371       ast_verbose("Sent Comfort Noise RTP packet to %s%s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
04372              ast_sockaddr_stringify(&remote_address),
04373              ice ? " (via ICE)" : "",
04374              AST_RTP_CN, rtp->seqno, rtp->lastdigitts, res - hdrlen);
04375    }
04376 
04377    rtp->seqno++;
04378 
04379    return res;
04380 }
04381 
04382 #ifdef HAVE_OPENSSL_SRTP
04383 static int ast_rtp_activate(struct ast_rtp_instance *instance)
04384 {
04385    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
04386 
04387    if (!rtp->ssl) {
04388       return 0;
04389    }
04390 
04391    SSL_do_handshake(rtp->ssl);
04392 
04393    dtls_srtp_check_pending(instance, rtp);
04394 
04395    return 0;
04396 }
04397 #endif
04398 
04399 static char *rtp_do_debug_ip(struct ast_cli_args *a)
04400 {
04401    char *arg = ast_strdupa(a->argv[4]);
04402    char *debughost = NULL;
04403    char *debugport = NULL;
04404 
04405    if (!ast_sockaddr_parse(&rtpdebugaddr, arg, 0) || !ast_sockaddr_split_hostport(arg, &debughost, &debugport, 0)) {
04406       ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
04407       return CLI_FAILURE;
04408    }
04409    rtpdebugport = (!ast_strlen_zero(debugport) && debugport[0] != '0');
04410    ast_cli(a->fd, "RTP Debugging Enabled for address: %s\n",
04411       ast_sockaddr_stringify(&rtpdebugaddr));
04412    rtpdebug = 1;
04413    return CLI_SUCCESS;
04414 }
04415 
04416 static char *rtcp_do_debug_ip(struct ast_cli_args *a)
04417 {
04418    char *arg = ast_strdupa(a->argv[4]);
04419    char *debughost = NULL;
04420    char *debugport = NULL;
04421 
04422    if (!ast_sockaddr_parse(&rtcpdebugaddr, arg, 0) || !ast_sockaddr_split_hostport(arg, &debughost, &debugport, 0)) {
04423       ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
04424       return CLI_FAILURE;
04425    }
04426    rtcpdebugport = (!ast_strlen_zero(debugport) && debugport[0] != '0');
04427    ast_cli(a->fd, "RTCP Debugging Enabled for address: %s\n",
04428       ast_sockaddr_stringify(&rtcpdebugaddr));
04429    rtcpdebug = 1;
04430    return CLI_SUCCESS;
04431 }
04432 
04433 static char *handle_cli_rtp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04434 {
04435    switch (cmd) {
04436    case CLI_INIT:
04437       e->command = "rtp set debug {on|off|ip}";
04438       e->usage =
04439          "Usage: rtp set debug {on|off|ip host[:port]}\n"
04440          "       Enable/Disable dumping of all RTP packets. If 'ip' is\n"
04441          "       specified, limit the dumped packets to those to and from\n"
04442          "       the specified 'host' with optional port.\n";
04443       return NULL;
04444    case CLI_GENERATE:
04445       return NULL;
04446    }
04447 
04448    if (a->argc == e->args) { /* set on or off */
04449       if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
04450          rtpdebug = 1;
04451          memset(&rtpdebugaddr, 0, sizeof(rtpdebugaddr));
04452          ast_cli(a->fd, "RTP Debugging Enabled\n");
04453          return CLI_SUCCESS;
04454       } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
04455          rtpdebug = 0;
04456          ast_cli(a->fd, "RTP Debugging Disabled\n");
04457          return CLI_SUCCESS;
04458       }
04459    } else if (a->argc == e->args +1) { /* ip */
04460       return rtp_do_debug_ip(a);
04461    }
04462 
04463    return CLI_SHOWUSAGE;   /* default, failure */
04464 }
04465 
04466 static char *handle_cli_rtcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04467 {
04468    switch (cmd) {
04469    case CLI_INIT:
04470       e->command = "rtcp set debug {on|off|ip}";
04471       e->usage =
04472          "Usage: rtcp set debug {on|off|ip host[:port]}\n"
04473          "       Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
04474          "       specified, limit the dumped packets to those to and from\n"
04475          "       the specified 'host' with optional port.\n";
04476       return NULL;
04477    case CLI_GENERATE:
04478       return NULL;
04479    }
04480 
04481    if (a->argc == e->args) { /* set on or off */
04482       if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
04483          rtcpdebug = 1;
04484          memset(&rtcpdebugaddr, 0, sizeof(rtcpdebugaddr));
04485          ast_cli(a->fd, "RTCP Debugging Enabled\n");
04486          return CLI_SUCCESS;
04487       } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
04488          rtcpdebug = 0;
04489          ast_cli(a->fd, "RTCP Debugging Disabled\n");
04490          return CLI_SUCCESS;
04491       }
04492    } else if (a->argc == e->args +1) { /* ip */
04493       return rtcp_do_debug_ip(a);
04494    }
04495 
04496    return CLI_SHOWUSAGE;   /* default, failure */
04497 }
04498 
04499 static char *handle_cli_rtcp_set_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04500 {
04501    switch (cmd) {
04502    case CLI_INIT:
04503       e->command = "rtcp set stats {on|off}";
04504       e->usage =
04505          "Usage: rtcp set stats {on|off}\n"
04506          "       Enable/Disable dumping of RTCP stats.\n";
04507       return NULL;
04508    case CLI_GENERATE:
04509       return NULL;
04510    }
04511 
04512    if (a->argc != e->args)
04513       return CLI_SHOWUSAGE;
04514 
04515    if (!strncasecmp(a->argv[e->args-1], "on", 2))
04516       rtcpstats = 1;
04517    else if (!strncasecmp(a->argv[e->args-1], "off", 3))
04518       rtcpstats = 0;
04519    else
04520       return CLI_SHOWUSAGE;
04521 
04522    ast_cli(a->fd, "RTCP Stats %s\n", rtcpstats ? "Enabled" : "Disabled");
04523    return CLI_SUCCESS;
04524 }
04525 
04526 static struct ast_cli_entry cli_rtp[] = {
04527    AST_CLI_DEFINE(handle_cli_rtp_set_debug,  "Enable/Disable RTP debugging"),
04528    AST_CLI_DEFINE(handle_cli_rtcp_set_debug, "Enable/Disable RTCP debugging"),
04529    AST_CLI_DEFINE(handle_cli_rtcp_set_stats, "Enable/Disable RTCP stats"),
04530 };
04531 
04532 static int rtp_reload(int reload)
04533 {
04534    struct ast_config *cfg;
04535    const char *s;
04536    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
04537 
04538    cfg = ast_config_load2("rtp.conf", "rtp", config_flags);
04539    if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
04540       return 0;
04541    }
04542 
04543    rtpstart = DEFAULT_RTP_START;
04544    rtpend = DEFAULT_RTP_END;
04545    dtmftimeout = DEFAULT_DTMF_TIMEOUT;
04546    strictrtp = DEFAULT_STRICT_RTP;
04547    learning_min_sequential = DEFAULT_LEARNING_MIN_SEQUENTIAL;
04548 
04549    /** This resource is not "reloaded" so much as unloaded and loaded again.
04550     * In the case of the TURN related variables, the memory referenced by a
04551     * previously loaded instance  *should* have been released when the
04552     * corresponding pool was destroyed. If at some point in the future this
04553     * resource were to support ACTUAL live reconfiguration and did NOT release
04554     * the pool this will cause a small memory leak.
04555     */
04556 
04557    icesupport = DEFAULT_ICESUPPORT;
04558    memset(&stunaddr, 0, sizeof(stunaddr));
04559 #ifdef USE_PJPROJECT
04560    turnport = DEFAULT_TURN_PORT;
04561    turnaddr = pj_str(NULL);
04562    turnusername = pj_str(NULL);
04563    turnpassword = pj_str(NULL);
04564 #endif
04565 
04566    if (cfg) {
04567       if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
04568          rtpstart = atoi(s);
04569          if (rtpstart < MINIMUM_RTP_PORT)
04570             rtpstart = MINIMUM_RTP_PORT;
04571          if (rtpstart > MAXIMUM_RTP_PORT)
04572             rtpstart = MAXIMUM_RTP_PORT;
04573       }
04574       if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
04575          rtpend = atoi(s);
04576          if (rtpend < MINIMUM_RTP_PORT)
04577             rtpend = MINIMUM_RTP_PORT;
04578          if (rtpend > MAXIMUM_RTP_PORT)
04579             rtpend = MAXIMUM_RTP_PORT;
04580       }
04581       if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
04582          rtcpinterval = atoi(s);
04583          if (rtcpinterval == 0)
04584             rtcpinterval = 0; /* Just so we're clear... it's zero */
04585          if (rtcpinterval < RTCP_MIN_INTERVALMS)
04586             rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
04587          if (rtcpinterval > RTCP_MAX_INTERVALMS)
04588             rtcpinterval = RTCP_MAX_INTERVALMS;
04589       }
04590       if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
04591 #ifdef SO_NO_CHECK
04592          nochecksums = ast_false(s) ? 1 : 0;
04593 #else
04594          if (ast_false(s))
04595             ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
04596 #endif
04597       }
04598       if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
04599          dtmftimeout = atoi(s);
04600          if ((dtmftimeout < 0) || (dtmftimeout > 64000)) {
04601             ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
04602                dtmftimeout, DEFAULT_DTMF_TIMEOUT);
04603             dtmftimeout = DEFAULT_DTMF_TIMEOUT;
04604          };
04605       }
04606       if ((s = ast_variable_retrieve(cfg, "general", "strictrtp"))) {
04607          strictrtp = ast_true(s);
04608       }
04609       if ((s = ast_variable_retrieve(cfg, "general", "probation"))) {
04610          if ((sscanf(s, "%d", &learning_min_sequential) <= 0) || learning_min_sequential <= 0) {
04611             ast_log(LOG_WARNING, "Value for 'probation' could not be read, using default of '%d' instead\n",
04612                DEFAULT_LEARNING_MIN_SEQUENTIAL);
04613          }
04614       }
04615       if ((s = ast_variable_retrieve(cfg, "general", "icesupport"))) {
04616          icesupport = ast_true(s);
04617       }
04618       if ((s = ast_variable_retrieve(cfg, "general", "stunaddr"))) {
04619          stunaddr.sin_port = htons(STANDARD_STUN_PORT);
04620          if (ast_parse_arg(s, PARSE_INADDR, &stunaddr)) {
04621             ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", s);
04622          }
04623       }
04624 #ifdef USE_PJPROJECT
04625       if ((s = ast_variable_retrieve(cfg, "general", "turnaddr"))) {
04626          struct sockaddr_in addr;
04627          addr.sin_port = htons(DEFAULT_TURN_PORT);
04628          if (ast_parse_arg(s, PARSE_INADDR, &addr)) {
04629             ast_log(LOG_WARNING, "Invalid TURN server address: %s\n", s);
04630          } else {
04631             pj_strdup2(pool, &turnaddr, ast_inet_ntoa(addr.sin_addr));
04632             /* ntohs() is not a bug here. The port number is used in host byte order with
04633              * a pjnat API. */
04634             turnport = ntohs(addr.sin_port);
04635          }
04636       }
04637       if ((s = ast_variable_retrieve(cfg, "general", "turnusername"))) {
04638          pj_strdup2(pool, &turnusername, s);
04639       }
04640       if ((s = ast_variable_retrieve(cfg, "general", "turnpassword"))) {
04641          pj_strdup2(pool, &turnpassword, s);
04642       }
04643 #endif
04644       ast_config_destroy(cfg);
04645    }
04646    if (rtpstart >= rtpend) {
04647       ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
04648       rtpstart = DEFAULT_RTP_START;
04649       rtpend = DEFAULT_RTP_END;
04650    }
04651    ast_verb(2, "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
04652    return 0;
04653 }
04654 
04655 static int reload_module(void)
04656 {
04657    rtp_reload(1);
04658    return 0;
04659 }
04660 
04661 static int load_module(void)
04662 {
04663 #ifdef USE_PJPROJECT
04664    pj_lock_t *lock;
04665 
04666    pj_log_set_level(0);
04667 
04668    if (pj_init() != PJ_SUCCESS) {
04669       return AST_MODULE_LOAD_DECLINE;
04670    }
04671 
04672    if (pjlib_util_init() != PJ_SUCCESS) {
04673       pj_shutdown();
04674       return AST_MODULE_LOAD_DECLINE;
04675    }
04676 
04677    if (pjnath_init() != PJ_SUCCESS) {
04678       pj_shutdown();
04679       return AST_MODULE_LOAD_DECLINE;
04680    }
04681 
04682    pj_caching_pool_init(&cachingpool, &pj_pool_factory_default_policy, 0);
04683 
04684    pool = pj_pool_create(&cachingpool.factory, "rtp", 512, 512, NULL);
04685 
04686    if (pj_timer_heap_create(pool, 100, &timerheap) != PJ_SUCCESS) {
04687       pj_caching_pool_destroy(&cachingpool);
04688       pj_shutdown();
04689       return AST_MODULE_LOAD_DECLINE;
04690    }
04691 
04692    if (pj_lock_create_recursive_mutex(pool, "rtp%p", &lock) != PJ_SUCCESS) {
04693       pj_caching_pool_destroy(&cachingpool);
04694       pj_shutdown();
04695       return AST_MODULE_LOAD_DECLINE;
04696    }
04697 
04698    pj_timer_heap_set_lock(timerheap, lock, PJ_TRUE);
04699 
04700    if (pj_ioqueue_create(pool, 16, &ioqueue) != PJ_SUCCESS) {
04701       pj_caching_pool_destroy(&cachingpool);
04702       pj_shutdown();
04703       return AST_MODULE_LOAD_DECLINE;
04704    }
04705 
04706    if (pj_thread_create(pool, "ice", &ice_worker_thread, NULL, 0, 0, &thread) != PJ_SUCCESS) {
04707       pj_caching_pool_destroy(&cachingpool);
04708       pj_shutdown();
04709       return AST_MODULE_LOAD_DECLINE;
04710    }
04711 #endif
04712 
04713    if (ast_rtp_engine_register(&asterisk_rtp_engine)) {
04714 #ifdef USE_PJPROJECT
04715       worker_terminate = 1;
04716       pj_thread_join(thread);
04717       pj_thread_destroy(thread);
04718       pj_caching_pool_destroy(&cachingpool);
04719       pj_shutdown();
04720 #endif
04721       return AST_MODULE_LOAD_DECLINE;
04722    }
04723 
04724    if (ast_cli_register_multiple(cli_rtp, ARRAY_LEN(cli_rtp))) {
04725 #ifdef USE_PJPROJECT
04726       worker_terminate = 1;
04727       pj_thread_join(thread);
04728       pj_thread_destroy(thread);
04729       ast_rtp_engine_unregister(&asterisk_rtp_engine);
04730       pj_caching_pool_destroy(&cachingpool);
04731       pj_shutdown();
04732 #endif
04733       return AST_MODULE_LOAD_DECLINE;
04734    }
04735 
04736    rtp_reload(0);
04737 
04738    return AST_MODULE_LOAD_SUCCESS;
04739 }
04740 
04741 static int unload_module(void)
04742 {
04743    ast_rtp_engine_unregister(&asterisk_rtp_engine);
04744    ast_cli_unregister_multiple(cli_rtp, ARRAY_LEN(cli_rtp));
04745 
04746 #ifdef USE_PJPROJECT
04747    worker_terminate = 1;
04748 
04749    pj_thread_register_check();
04750 
04751    pj_thread_join(thread);
04752    pj_thread_destroy(thread);
04753 
04754    pj_caching_pool_destroy(&cachingpool);
04755    pj_shutdown();
04756 #endif
04757 
04758    return 0;
04759 }
04760 
04761 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Asterisk RTP Stack",
04762       .load = load_module,
04763       .unload = unload_module,
04764       .reload = reload_module,
04765       .load_pri = AST_MODPRI_CHANNEL_DEPEND,
04766       );