/
res_rtp_asterisk.c
4565 lines (3816 loc) · 153 KB
/
res_rtp_asterisk.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 1999 - 2008, Digium, Inc.
*
* Mark Spencer <markster@digium.com>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*!
* \file
*
* \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
*
* \author Mark Spencer <markster@digium.com>
*
* \note RTP is defined in RFC 3550.
*
* \ingroup rtp_engines
*/
/*** MODULEINFO
<depend>uuid</depend>
<support_level>core</support_level>
***/
#include "asterisk.h"
ASTERISK_FILE_VERSION(__FILE__, "$Revision: 385356 $")
#include <sys/time.h>
#include <signal.h>
#include <fcntl.h>
#ifdef HAVE_OPENSSL_SRTP
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#endif
/* Asterisk discourages the use of bzero in favor of memset, in fact if you try to use bzero it will tell you to use memset. As a result bzero has to be undefined
* here since it is used internally by pjlib. The only other option would be to modify pjlib... which won't happen. */
#undef bzero
#define bzero bzero
#include "pjlib.h"
#include "pjlib-util.h"
#include "pjnath.h"
#include "asterisk/stun.h"
#include "asterisk/pbx.h"
#include "asterisk/frame.h"
#include "asterisk/channel.h"
#include "asterisk/acl.h"
#include "asterisk/config.h"
#include "asterisk/lock.h"
#include "asterisk/utils.h"
#include "asterisk/cli.h"
#include "asterisk/manager.h"
#include "asterisk/unaligned.h"
#include "asterisk/module.h"
#include "asterisk/rtp_engine.h"
#define MAX_TIMESTAMP_SKEW 640
#define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
#define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
#define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
#define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
#define DEFAULT_RTP_START 5000 /*!< Default port number to start allocating RTP ports from */
#define DEFAULT_RTP_END 31000 /*!< Default maximum port number to end allocating RTP ports at */
#define MINIMUM_RTP_PORT 1024 /*!< Minimum port number to accept */
#define MAXIMUM_RTP_PORT 65535 /*!< Maximum port number to accept */
#define DEFAULT_TURN_PORT 34780
#define TURN_ALLOCATION_WAIT_TIME 2000
#define RTCP_PT_FUR 192
#define RTCP_PT_SR 200
#define RTCP_PT_RR 201
#define RTCP_PT_SDES 202
#define RTCP_PT_BYE 203
#define RTCP_PT_APP 204
#define RTP_MTU 1200
#define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000)) /*!< samples */
#define ZFONE_PROFILE_ID 0x505a
#define DEFAULT_LEARNING_MIN_SEQUENTIAL 4
#define SRTP_MASTER_KEY_LEN 16
#define SRTP_MASTER_SALT_LEN 14
#define SRTP_MASTER_LEN (SRTP_MASTER_KEY_LEN + SRTP_MASTER_SALT_LEN)
enum strict_rtp_state {
STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
STRICT_RTP_LEARN, /*! Accept next packet as source */
STRICT_RTP_CLOSED, /*! Drop all RTP packets not coming from source that was learned */
};
#define DEFAULT_STRICT_RTP STRICT_RTP_CLOSED
#define DEFAULT_ICESUPPORT 1
extern struct ast_srtp_res *res_srtp;
extern struct ast_srtp_policy_res *res_srtp_policy;
static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
static int rtpstart = DEFAULT_RTP_START; /*!< First port for RTP sessions (set in rtp.conf) */
static int rtpend = DEFAULT_RTP_END; /*!< Last port for RTP sessions (set in rtp.conf) */
static int rtpdebug; /*!< Are we debugging? */
static int rtcpdebug; /*!< Are we debugging RTCP? */
static int rtcpstats; /*!< Are we debugging RTCP? */
static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
static struct ast_sockaddr rtpdebugaddr; /*!< Debug packets to/from this host */
static struct ast_sockaddr rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
static int rtpdebugport; /*< Debug only RTP packets from IP or IP+Port if port is > 0 */
static int rtcpdebugport; /*< Debug only RTCP packets from IP or IP+Port if port is > 0 */
#ifdef SO_NO_CHECK
static int nochecksums;
#endif
static int strictrtp = DEFAULT_STRICT_RTP; /*< Only accept RTP frames from a defined source. If we receive an indication of a changing source, enter learning mode. */
static int learning_min_sequential = DEFAULT_LEARNING_MIN_SEQUENTIAL; /*< Number of sequential RTP frames needed from a single source during learning mode to accept new source. */
static int icesupport = DEFAULT_ICESUPPORT;
static struct sockaddr_in stunaddr;
static pj_str_t turnaddr;
static int turnport = DEFAULT_TURN_PORT;
static pj_str_t turnusername;
static pj_str_t turnpassword;
/*! \brief Pool factory used by pjlib to allocate memory. */
static pj_caching_pool cachingpool;
/*! \brief Pool used by pjlib functions which require memory allocation. */
static pj_pool_t *pool;
/*! \brief I/O queue for TURN relay traffic */
static pj_ioqueue_t *ioqueue;
/*! \brief Timer heap for ICE and TURN stuff */
static pj_timer_heap_t *timerheap;
/*! \brief Worker thread for ICE/TURN */
static pj_thread_t *thread;
/*! \brief Notification that the ICE/TURN worker thread should stop */
static int worker_terminate;
#define FLAG_3389_WARNING (1 << 0)
#define FLAG_NAT_ACTIVE (3 << 1)
#define FLAG_NAT_INACTIVE (0 << 1)
#define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
#define FLAG_NEED_MARKER_BIT (1 << 3)
#define FLAG_DTMF_COMPENSATE (1 << 4)
#define TRANSPORT_SOCKET_RTP 1
#define TRANSPORT_SOCKET_RTCP 2
#define TRANSPORT_TURN_RTP 3
#define TRANSPORT_TURN_RTCP 4
#define COMPONENT_RTP 1
#define COMPONENT_RTCP 2
/*! \brief RTP learning mode tracking information */
struct rtp_learning_info {
int max_seq; /*!< The highest sequence number received */
int packets; /*!< The number of remaining packets before the source is accepted */
};
/*! \brief RTP session description */
struct ast_rtp {
int s;
struct ast_frame f;
unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
unsigned int themssrc; /*!< Their SSRC */
unsigned int rxssrc;
unsigned int lastts;
unsigned int lastrxts;
unsigned int lastividtimestamp;
unsigned int lastovidtimestamp;
unsigned int lastitexttimestamp;
unsigned int lastotexttimestamp;
unsigned int lasteventseqn;
int lastrxseqno; /*!< Last received sequence number */
unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
unsigned int rxcount; /*!< How many packets have we received? */
unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
unsigned int txcount; /*!< How many packets have we sent? */
unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
unsigned int cycles; /*!< Shifted count of sequence number cycles */
double rxjitter; /*!< Interarrival jitter at the moment in seconds */
double rxtransit; /*!< Relative transit time for previous packet */
struct ast_format lasttxformat;
struct ast_format lastrxformat;
int rtptimeout; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
int rtpholdtimeout; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
int rtpkeepalive; /*!< Send RTP comfort noice packets for keepalive */
/* DTMF Reception Variables */
char resp; /*!< The current digit being processed */
unsigned int last_seqno; /*!< The last known sequence number for any DTMF packet */
unsigned int last_end_timestamp; /*!< The last known timestamp received from an END packet */
unsigned int dtmf_duration; /*!< Total duration in samples since the digit start event */
unsigned int dtmf_timeout; /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
unsigned int dtmfsamples;
enum ast_rtp_dtmf_mode dtmfmode; /*!< The current DTMF mode of the RTP stream */
/* DTMF Transmission Variables */
unsigned int lastdigitts;
char sending_digit; /*!< boolean - are we sending digits */
char send_digit; /*!< digit we are sending */
int send_payload;
int send_duration;
unsigned int flags;
struct timeval rxcore;
struct timeval txcore;
double drxcore; /*!< The double representation of the first received packet */
struct timeval lastrx; /*!< timeval when we last received a packet */
struct timeval dtmfmute;
struct ast_smoother *smoother;
int *ioid;
unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
unsigned short rxseqno;
struct ast_sched_context *sched;
struct io_context *io;
void *data;
struct ast_rtcp *rtcp;
struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
struct ast_sockaddr strict_rtp_address; /*!< Remote address information for strict RTP purposes */
struct ast_sockaddr alt_rtp_address; /*!<Alternate remote address information */
/*
* Learning mode values based on pjmedia's probation mode. Many of these values are redundant to the above,
* but these are in place to keep learning mode sequence values sealed from their normal counterparts.
*/
struct rtp_learning_info rtp_source_learn; /* Learning mode track for the expected RTP source */
struct rtp_learning_info alt_source_learn; /* Learning mode tracking for a new RTP source after one has been chosen */
struct rtp_red *red;
pj_ice_sess *ice; /*!< ICE session */
pj_turn_sock *turn_rtp; /*!< RTP TURN relay */
pj_turn_sock *turn_rtcp; /*!< RTCP TURN relay */
ast_mutex_t lock; /*!< Lock for synchronization purposes */
pj_turn_state_t turn_state; /*!< Current state of the TURN relay session */
ast_cond_t cond; /*!< Condition for signaling */
unsigned int passthrough:1; /*!< Bit to indicate that the received packet should be passed through */
unsigned int ice_started:1; /*!< Bit to indicate ICE connectivity checks have started */
char remote_ufrag[256]; /*!< The remote ICE username */
char remote_passwd[256]; /*!< The remote ICE password */
char local_ufrag[256]; /*!< The local ICE username */
char local_passwd[256]; /*!< The local ICE password */
struct ao2_container *local_candidates; /*!< The local ICE candidates */
struct ao2_container *remote_candidates; /*!< The remote ICE candidates */
#ifdef HAVE_OPENSSL_SRTP
SSL_CTX *ssl_ctx; /*!< SSL context */
SSL *ssl; /*!< SSL session */
BIO *read_bio; /*!< Memory buffer for reading */
BIO *write_bio; /*!< Memory buffer for writing */
enum ast_rtp_dtls_setup dtls_setup; /*!< Current setup state */
enum ast_srtp_suite suite; /*!< SRTP crypto suite */
char local_fingerprint[160]; /*!< Fingerprint of our certificate */
unsigned char remote_fingerprint[EVP_MAX_MD_SIZE]; /*!< Fingerprint of the peer certificate */
enum ast_rtp_dtls_connection connection; /*!< Whether this is a new or existing connection */
unsigned int dtls_failure:1; /*!< Failure occurred during DTLS negotiation */
unsigned int rekey; /*!< Interval at which to renegotiate and rekey */
int rekeyid; /*!< Scheduled item id for rekeying */
#endif
};
/*!
* \brief Structure defining an RTCP session.
*
* The concept "RTCP session" is not defined in RFC 3550, but since
* this structure is analogous to ast_rtp, which tracks a RTP session,
* it is logical to think of this as a RTCP session.
*
* RTCP packet is defined on page 9 of RFC 3550.
*
*/
struct ast_rtcp {
int rtcp_info;
int s; /*!< Socket */
struct ast_sockaddr us; /*!< Socket representation of the local endpoint. */
struct ast_sockaddr them; /*!< Socket representation of the remote endpoint. */
unsigned int soc; /*!< What they told us */
unsigned int spc; /*!< What they told us */
unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
struct timeval rxlsr; /*!< Time when we got their last SR */
struct timeval txlsr; /*!< Time when we sent or last SR*/
unsigned int expected_prior; /*!< no. packets in previous interval */
unsigned int received_prior; /*!< no. packets received in previous interval */
int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
unsigned int sr_count; /*!< number of SRs we've sent */
unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
double accumulated_transit; /*!< accumulated a-dlsr-lsr */
double rtt; /*!< Last reported rtt */
unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
unsigned int reported_lost; /*!< Reported lost packets in their RR */
double reported_maxjitter;
double reported_minjitter;
double reported_normdev_jitter;
double reported_stdev_jitter;
unsigned int reported_jitter_count;
double reported_maxlost;
double reported_minlost;
double reported_normdev_lost;
double reported_stdev_lost;
double rxlost;
double maxrxlost;
double minrxlost;
double normdev_rxlost;
double stdev_rxlost;
unsigned int rxlost_count;
double maxrxjitter;
double minrxjitter;
double normdev_rxjitter;
double stdev_rxjitter;
unsigned int rxjitter_count;
double maxrtt;
double minrtt;
double normdevrtt;
double stdevrtt;
unsigned int rtt_count;
};
struct rtp_red {
struct ast_frame t140; /*!< Primary data */
struct ast_frame t140red; /*!< Redundant t140*/
unsigned char pt[AST_RED_MAX_GENERATION]; /*!< Payload types for redundancy data */
unsigned char ts[AST_RED_MAX_GENERATION]; /*!< Time stamps */
unsigned char len[AST_RED_MAX_GENERATION]; /*!< length of each generation */
int num_gen; /*!< Number of generations */
int schedid; /*!< Timer id */
int ti; /*!< How long to buffer data before send */
unsigned char t140red_data[64000];
unsigned char buf_data[64000]; /*!< buffered primary data */
int hdrlen;
long int prev_ts;
};
AST_LIST_HEAD_NOLOCK(frame_list, ast_frame);
/* Forward Declarations */
static int ast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data);
static int ast_rtp_destroy(struct ast_rtp_instance *instance);
static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration);
static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode);
static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance);
static void ast_rtp_update_source(struct ast_rtp_instance *instance);
static void ast_rtp_change_source(struct ast_rtp_instance *instance);
static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
static void ast_rtp_alt_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username);
static void ast_rtp_stop(struct ast_rtp_instance *instance);
static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char* desc);
static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level);
#ifdef HAVE_OPENSSL_SRTP
static int ast_rtp_activate(struct ast_rtp_instance *instance);
#endif
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);
/*! \brief Destructor for locally created ICE candidates */
static void ast_rtp_ice_candidate_destroy(void *obj)
{
struct ast_rtp_engine_ice_candidate *candidate = obj;
if (candidate->foundation) {
ast_free(candidate->foundation);
}
if (candidate->transport) {
ast_free(candidate->transport);
}
}
static void ast_rtp_ice_set_authentication(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
if (!ast_strlen_zero(ufrag)) {
ast_copy_string(rtp->remote_ufrag, ufrag, sizeof(rtp->remote_ufrag));
}
if (!ast_strlen_zero(password)) {
ast_copy_string(rtp->remote_passwd, password, sizeof(rtp->remote_passwd));
}
}
static void ast_rtp_ice_add_remote_candidate(struct ast_rtp_instance *instance, const struct ast_rtp_engine_ice_candidate *candidate)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
struct ast_rtp_engine_ice_candidate *remote_candidate;
if (!rtp->remote_candidates && !(rtp->remote_candidates = ao2_container_alloc(1, NULL, NULL))) {
return;
}
/* If this is going to exceed the maximum number of ICE candidates don't even add it */
if (ao2_container_count(rtp->remote_candidates) == PJ_ICE_MAX_CAND) {
return;
}
if (!(remote_candidate = ao2_alloc(sizeof(*remote_candidate), ast_rtp_ice_candidate_destroy))) {
return;
}
remote_candidate->foundation = ast_strdup(candidate->foundation);
remote_candidate->id = candidate->id;
remote_candidate->transport = ast_strdup(candidate->transport);
remote_candidate->priority = candidate->priority;
ast_sockaddr_copy(&remote_candidate->address, &candidate->address);
ast_sockaddr_copy(&remote_candidate->relay_address, &candidate->relay_address);
remote_candidate->type = candidate->type;
ao2_link(rtp->remote_candidates, remote_candidate);
ao2_ref(remote_candidate, -1);
}
AST_THREADSTORAGE(pj_thread_storage);
/*! \brief Function used to check if the calling thread is registered with pjlib. If it is not it will be registered. */
static void pj_thread_register_check(void)
{
pj_thread_desc *desc;
pj_thread_t *thread;
if (pj_thread_is_registered() == PJ_TRUE) {
return;
}
desc = ast_threadstorage_get(&pj_thread_storage, sizeof(pj_thread_desc));
if (!desc) {
ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage. Expect awful things to occur\n");
return;
}
pj_bzero(*desc, sizeof(*desc));
if (pj_thread_register("Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
ast_log(LOG_ERROR, "Coudln't register thread with PJLIB.\n");
}
return;
}
/*! \brief Helper function which updates an ast_sockaddr with the candidate used for the component */
static void update_address_with_ice_candidate(struct ast_rtp *rtp, int component, struct ast_sockaddr *cand_address)
{
char address[PJ_INET6_ADDRSTRLEN];
if (!rtp->ice || (component < 1) || !rtp->ice->comp[component - 1].valid_check) {
return;
}
ast_sockaddr_parse(cand_address, pj_sockaddr_print(&rtp->ice->comp[component - 1].valid_check->rcand->addr, address, sizeof(address), 0), 0);
ast_sockaddr_set_port(cand_address, pj_sockaddr_get_port(&rtp->ice->comp[component - 1].valid_check->rcand->addr));
}
static void ast_rtp_ice_start(struct ast_rtp_instance *instance)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
pj_str_t ufrag = pj_str(rtp->remote_ufrag), passwd = pj_str(rtp->remote_passwd);
pj_ice_sess_cand candidates[PJ_ICE_MAX_CAND];
struct ao2_iterator i;
struct ast_rtp_engine_ice_candidate *candidate;
int cand_cnt = 0;
if (!rtp->ice || !rtp->remote_candidates || rtp->ice_started) {
return;
}
pj_thread_register_check();
i = ao2_iterator_init(rtp->remote_candidates, 0);
while ((candidate = ao2_iterator_next(&i)) && (cand_cnt < PJ_ICE_MAX_CAND)) {
pj_str_t address;
pj_strdup2(rtp->ice->pool, &candidates[cand_cnt].foundation, candidate->foundation);
candidates[cand_cnt].comp_id = candidate->id;
candidates[cand_cnt].prio = candidate->priority;
pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->address)), &candidates[cand_cnt].addr);
if (!ast_sockaddr_isnull(&candidate->relay_address)) {
pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->relay_address)), &candidates[cand_cnt].rel_addr);
}
if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_HOST;
} else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_SRFLX;
} else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_RELAYED;
}
if (candidate->id == COMPONENT_RTP && rtp->turn_rtp) {
pj_turn_sock_set_perm(rtp->turn_rtp, 1, &candidates[cand_cnt].addr, 1);
} else if (candidate->id == COMPONENT_RTCP && rtp->turn_rtcp) {
pj_turn_sock_set_perm(rtp->turn_rtcp, 1, &candidates[cand_cnt].addr, 1);
}
cand_cnt++;
}
ao2_iterator_destroy(&i);
if (pj_ice_sess_create_check_list(rtp->ice, &ufrag, &passwd, ao2_container_count(rtp->remote_candidates), &candidates[0]) == PJ_SUCCESS) {
pj_ice_sess_start_check(rtp->ice);
pj_timer_heap_poll(timerheap, NULL);
rtp->ice_started = 1;
rtp->strict_rtp_state = STRICT_RTP_OPEN;
}
}
static void ast_rtp_ice_stop(struct ast_rtp_instance *instance)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
if (!rtp->ice) {
return;
}
pj_thread_register_check();
pj_ice_sess_destroy(rtp->ice);
rtp->ice = NULL;
}
static const char *ast_rtp_ice_get_ufrag(struct ast_rtp_instance *instance)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
return rtp->local_ufrag;
}
static const char *ast_rtp_ice_get_password(struct ast_rtp_instance *instance)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
return rtp->local_passwd;
}
static struct ao2_container *ast_rtp_ice_get_local_candidates(struct ast_rtp_instance *instance)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
if (rtp->local_candidates) {
ao2_ref(rtp->local_candidates, +1);
}
return rtp->local_candidates;
}
static void ast_rtp_ice_lite(struct ast_rtp_instance *instance)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
if (!rtp->ice) {
return;
}
pj_thread_register_check();
pj_ice_sess_change_role(rtp->ice, PJ_ICE_SESS_ROLE_CONTROLLING);
}
static int ice_candidate_cmp(void *obj, void *arg, int flags)
{
struct ast_rtp_engine_ice_candidate *candidate1 = obj, *candidate2 = arg;
if ((strcmp(candidate1->foundation, candidate2->foundation)) ||
(candidate1->id != candidate2->id) ||
(ast_sockaddr_cmp(&candidate1->address, &candidate2->address)) ||
(candidate1->type != candidate1->type)) {
return 0;
}
return CMP_MATCH | CMP_STOP;
}
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,
const pj_sockaddr_t *addr, const pj_sockaddr_t *base_addr, const pj_sockaddr_t *rel_addr, int addr_len)
{
pj_str_t foundation;
struct ast_rtp_engine_ice_candidate *candidate, *existing;
char address[PJ_INET6_ADDRSTRLEN];
pj_thread_register_check();
pj_ice_calc_foundation(rtp->ice->pool, &foundation, type, addr);
if (!rtp->local_candidates && !(rtp->local_candidates = ao2_container_alloc(1, NULL, ice_candidate_cmp))) {
return;
}
if (!(candidate = ao2_alloc(sizeof(*candidate), ast_rtp_ice_candidate_destroy))) {
return;
}
candidate->foundation = ast_strndup(pj_strbuf(&foundation), pj_strlen(&foundation));
candidate->id = comp_id;
candidate->transport = ast_strdup("UDP");
ast_sockaddr_parse(&candidate->address, pj_sockaddr_print(addr, address, sizeof(address), 0), 0);
ast_sockaddr_set_port(&candidate->address, pj_sockaddr_get_port(addr));
if (rel_addr) {
ast_sockaddr_parse(&candidate->relay_address, pj_sockaddr_print(rel_addr, address, sizeof(address), 0), 0);
ast_sockaddr_set_port(&candidate->relay_address, pj_sockaddr_get_port(rel_addr));
}
if (type == PJ_ICE_CAND_TYPE_HOST) {
candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
} else if (type == PJ_ICE_CAND_TYPE_SRFLX) {
candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
} else if (type == PJ_ICE_CAND_TYPE_RELAYED) {
candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
}
if ((existing = ao2_find(rtp->local_candidates, candidate, OBJ_POINTER))) {
ao2_ref(existing, -1);
ao2_ref(candidate, -1);
return;
}
if (pj_ice_sess_add_cand(rtp->ice, comp_id, transport_id, type, local_pref, &foundation, addr, addr, rel_addr, addr_len, NULL) != PJ_SUCCESS) {
ao2_ref(candidate, -1);
return;
}
/* By placing the candidate into the ICE session it will have produced the priority, so update the local candidate with it */
candidate->priority = rtp->ice->lcand[rtp->ice->lcand_cnt - 1].prio;
ao2_link(rtp->local_candidates, candidate);
ao2_ref(candidate, -1);
}
static char *generate_random_string(char *buf, size_t size)
{
long val[4];
int x;
for (x=0; x<4; x++)
val[x] = ast_random();
snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
return buf;
}
/* ICE RTP Engine interface declaration */
static struct ast_rtp_engine_ice ast_rtp_ice = {
.set_authentication = ast_rtp_ice_set_authentication,
.add_remote_candidate = ast_rtp_ice_add_remote_candidate,
.start = ast_rtp_ice_start,
.stop = ast_rtp_ice_stop,
.get_ufrag = ast_rtp_ice_get_ufrag,
.get_password = ast_rtp_ice_get_password,
.get_local_candidates = ast_rtp_ice_get_local_candidates,
.ice_lite = ast_rtp_ice_lite,
};
#ifdef HAVE_OPENSSL_SRTP
static void dtls_info_callback(const SSL *ssl, int where, int ret)
{
struct ast_rtp *rtp = SSL_get_ex_data(ssl, 0);
/* We only care about alerts */
if (!(where & SSL_CB_ALERT)) {
return;
}
rtp->dtls_failure = 1;
}
static int ast_rtp_dtls_set_configuration(struct ast_rtp_instance *instance, const struct ast_rtp_dtls_cfg *dtls_cfg)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
if (!dtls_cfg->enabled) {
return 0;
}
if (!ast_rtp_engine_srtp_is_registered()) {
return -1;
}
if (!(rtp->ssl_ctx = SSL_CTX_new(DTLSv1_method()))) {
return -1;
}
SSL_CTX_set_verify(rtp->ssl_ctx, dtls_cfg->verify ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE, NULL);
if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_80) {
SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_80");
} else if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_32) {
SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_32");
} else {
ast_log(LOG_ERROR, "Unsupported suite specified for DTLS-SRTP on RTP instance '%p'\n", instance);
goto error;
}
if (!ast_strlen_zero(dtls_cfg->certfile)) {
char *private = ast_strlen_zero(dtls_cfg->pvtfile) ? dtls_cfg->certfile : dtls_cfg->pvtfile;
BIO *certbio;
X509 *cert;
unsigned int size, i;
unsigned char fingerprint[EVP_MAX_MD_SIZE];
char *local_fingerprint = rtp->local_fingerprint;
if (!SSL_CTX_use_certificate_file(rtp->ssl_ctx, dtls_cfg->certfile, SSL_FILETYPE_PEM)) {
ast_log(LOG_ERROR, "Specified certificate file '%s' for RTP instance '%p' could not be used\n",
dtls_cfg->certfile, instance);
goto error;
}
if (!SSL_CTX_use_PrivateKey_file(rtp->ssl_ctx, private, SSL_FILETYPE_PEM) ||
!SSL_CTX_check_private_key(rtp->ssl_ctx)) {
ast_log(LOG_ERROR, "Specified private key file '%s' for RTP instance '%p' could not be used\n",
private, instance);
goto error;
}
if (!(certbio = BIO_new(BIO_s_file()))) {
ast_log(LOG_ERROR, "Failed to allocate memory for certificate fingerprinting on RTP instance '%p'\n",
instance);
goto error;
}
if (!BIO_read_filename(certbio, dtls_cfg->certfile) ||
!(cert = PEM_read_bio_X509(certbio, NULL, 0, NULL)) ||
!X509_digest(cert, EVP_sha1(), fingerprint, &size) ||
!size) {
ast_log(LOG_ERROR, "Could not produce fingerprint from certificate '%s' for RTP instance '%p'\n",
dtls_cfg->certfile, instance);
BIO_free_all(certbio);
goto error;
}
for (i = 0; i < size; i++) {
sprintf(local_fingerprint, "%.2X:", fingerprint[i]);
local_fingerprint += 3;
}
*(local_fingerprint-1) = 0;
BIO_free_all(certbio);
}
if (!ast_strlen_zero(dtls_cfg->cipher)) {
if (!SSL_CTX_set_cipher_list(rtp->ssl_ctx, dtls_cfg->cipher)) {
ast_log(LOG_ERROR, "Invalid cipher specified in cipher list '%s' for RTP instance '%p'\n",
dtls_cfg->cipher, instance);
goto error;
}
}
if (!ast_strlen_zero(dtls_cfg->cafile) || !ast_strlen_zero(dtls_cfg->capath)) {
if (!SSL_CTX_load_verify_locations(rtp->ssl_ctx, S_OR(dtls_cfg->cafile, NULL), S_OR(dtls_cfg->capath, NULL))) {
ast_log(LOG_ERROR, "Invalid certificate authority file '%s' or path '%s' specified for RTP instance '%p'\n",
S_OR(dtls_cfg->cafile, ""), S_OR(dtls_cfg->capath, ""), instance);
goto error;
}
}
rtp->rekey = dtls_cfg->rekey;
rtp->dtls_setup = dtls_cfg->default_setup;
rtp->suite = dtls_cfg->suite;
if (!(rtp->ssl = SSL_new(rtp->ssl_ctx))) {
ast_log(LOG_ERROR, "Failed to allocate memory for SSL context on RTP instance '%p'\n",
instance);
goto error;
}
SSL_set_ex_data(rtp->ssl, 0, rtp);
SSL_set_info_callback(rtp->ssl, dtls_info_callback);
if (!(rtp->read_bio = BIO_new(BIO_s_mem()))) {
ast_log(LOG_ERROR, "Failed to allocate memory for inbound SSL traffic on RTP instance '%p'\n",
instance);
goto error;
}
BIO_set_mem_eof_return(rtp->read_bio, -1);
if (!(rtp->write_bio = BIO_new(BIO_s_mem()))) {
ast_log(LOG_ERROR, "Failed to allocate memory for outbound SSL traffic on RTP instance '%p'\n",
instance);
goto error;
}
BIO_set_mem_eof_return(rtp->write_bio, -1);
SSL_set_bio(rtp->ssl, rtp->read_bio, rtp->write_bio);
if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
SSL_set_accept_state(rtp->ssl);
} else {
SSL_set_connect_state(rtp->ssl);
}
rtp->connection = AST_RTP_DTLS_CONNECTION_NEW;
return 0;
error:
if (rtp->read_bio) {
BIO_free(rtp->read_bio);
rtp->read_bio = NULL;
}
if (rtp->write_bio) {
BIO_free(rtp->write_bio);
rtp->write_bio = NULL;
}
if (rtp->ssl) {
SSL_free(rtp->ssl);
rtp->ssl = NULL;
}
SSL_CTX_free(rtp->ssl_ctx);
rtp->ssl_ctx = NULL;
return -1;
}
static int ast_rtp_dtls_active(struct ast_rtp_instance *instance)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
return !rtp->ssl_ctx ? 0 : 1;
}
static void ast_rtp_dtls_stop(struct ast_rtp_instance *instance)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
if (rtp->ssl_ctx) {
SSL_CTX_free(rtp->ssl_ctx);
rtp->ssl_ctx = NULL;
}
if (rtp->ssl) {
SSL_free(rtp->ssl);
rtp->ssl = NULL;
}
}
static void ast_rtp_dtls_reset(struct ast_rtp_instance *instance)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
/* If the SSL session is not yet finalized don't bother resetting */
if (!SSL_is_init_finished(rtp->ssl)) {
return;
}
SSL_shutdown(rtp->ssl);
rtp->connection = AST_RTP_DTLS_CONNECTION_NEW;
}
static enum ast_rtp_dtls_connection ast_rtp_dtls_get_connection(struct ast_rtp_instance *instance)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
return rtp->connection;
}
static enum ast_rtp_dtls_setup ast_rtp_dtls_get_setup(struct ast_rtp_instance *instance)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
return rtp->dtls_setup;
}
static void ast_rtp_dtls_set_setup(struct ast_rtp_instance *instance, enum ast_rtp_dtls_setup setup)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
enum ast_rtp_dtls_setup old = rtp->dtls_setup;
switch (setup) {
case AST_RTP_DTLS_SETUP_ACTIVE:
rtp->dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
break;
case AST_RTP_DTLS_SETUP_PASSIVE:
rtp->dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
break;
case AST_RTP_DTLS_SETUP_ACTPASS:
/* We can't respond to an actpass setup with actpass ourselves... so respond with active, as we can initiate connections */
if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
rtp->dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
}
break;
case AST_RTP_DTLS_SETUP_HOLDCONN:
rtp->dtls_setup = AST_RTP_DTLS_SETUP_HOLDCONN;
break;
default:
/* This should never occur... if it does exit early as we don't know what state things are in */
return;
}
/* If the setup state did not change we go on as if nothing happened */
if (old == rtp->dtls_setup) {
return;
}
/* If they don't want us to establish a connection wait until later */
if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_HOLDCONN) {
return;
}
if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
SSL_set_connect_state(rtp->ssl);
} else if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
SSL_set_accept_state(rtp->ssl);
} else {
return;
}
}
static void ast_rtp_dtls_set_fingerprint(struct ast_rtp_instance *instance, enum ast_rtp_dtls_hash hash, const char *fingerprint)
{
char *tmp = ast_strdupa(fingerprint), *value;
int pos = 0;
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
if (hash != AST_RTP_DTLS_HASH_SHA1) {
return;
}
while ((value = strsep(&tmp, ":")) && (pos != (EVP_MAX_MD_SIZE - 1))) {
sscanf(value, "%02x", (unsigned int*)&rtp->remote_fingerprint[pos++]);
}
}
static const char *ast_rtp_dtls_get_fingerprint(struct ast_rtp_instance *instance, enum ast_rtp_dtls_hash hash)
{
struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
if (hash != AST_RTP_DTLS_HASH_SHA1) {
return NULL;
}
return rtp->local_fingerprint;
}
/* DTLS RTP Engine interface declaration */
static struct ast_rtp_engine_dtls ast_rtp_dtls = {
.set_configuration = ast_rtp_dtls_set_configuration,
.active = ast_rtp_dtls_active,
.stop = ast_rtp_dtls_stop,
.reset = ast_rtp_dtls_reset,
.get_connection = ast_rtp_dtls_get_connection,
.get_setup = ast_rtp_dtls_get_setup,
.set_setup = ast_rtp_dtls_set_setup,
.set_fingerprint = ast_rtp_dtls_set_fingerprint,
.get_fingerprint = ast_rtp_dtls_get_fingerprint,
};
#endif
/* RTP Engine Declaration */