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