forked from meetecho/janus-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ice.c
5016 lines (4874 loc) · 210 KB
/
ice.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
/*! \file ice.c
* \author Lorenzo Miniero <[email protected]>
* \copyright GNU General Public License v3
* \brief ICE/STUN/TURN processing
* \details Implementation (based on libnice) of the ICE process. The
* code handles the whole ICE process, from the gathering of candidates
* to the final setup of a virtual channel RTP and RTCP can be transported
* on. Incoming RTP and RTCP packets from peers are relayed to the associated
* plugins by means of the incoming_rtp and incoming_rtcp callbacks. Packets
* to be sent to peers are relayed by peers invoking the relay_rtp and
* relay_rtcp core callbacks instead.
*
* \ingroup protocols
* \ref protocols
*/
#include <ifaddrs.h>
#include <poll.h>
#include <net/if.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netdb.h>
#include <fcntl.h>
#include <stun/usages/bind.h>
#include <nice/debug.h>
#include "janus.h"
#include "debug.h"
#include "ice.h"
#include "turnrest.h"
#include "sdp.h"
#include "rtpsrtp.h"
#include "rtcp.h"
#include "apierror.h"
#include "ip-utils.h"
#include "events.h"
/* STUN server/port, if any */
static char *janus_stun_server = NULL;
static uint16_t janus_stun_port = 0;
char *janus_ice_get_stun_server(void) {
return janus_stun_server;
}
uint16_t janus_ice_get_stun_port(void) {
return janus_stun_port;
}
/* TURN server/port and credentials, if any */
static char *janus_turn_server = NULL;
static uint16_t janus_turn_port = 0;
static char *janus_turn_user = NULL, *janus_turn_pwd = NULL;
static NiceRelayType janus_turn_type = NICE_RELAY_TYPE_TURN_UDP;
char *janus_ice_get_turn_server(void) {
return janus_turn_server;
}
uint16_t janus_ice_get_turn_port(void) {
return janus_turn_port;
}
/* TURN REST API support, if any */
char *janus_ice_get_turn_rest_api(void) {
#ifndef HAVE_TURNRESTAPI
return NULL;
#else
return (char *)janus_turnrest_get_backend();
#endif
}
/* ICE-Lite status */
static gboolean janus_ice_lite_enabled;
gboolean janus_ice_is_ice_lite_enabled(void) {
return janus_ice_lite_enabled;
}
/* ICE-TCP support (only libnice >= 0.1.8, currently broken) */
static gboolean janus_ice_tcp_enabled;
gboolean janus_ice_is_ice_tcp_enabled(void) {
return janus_ice_tcp_enabled;
}
/* Full-trickle support */
static gboolean janus_full_trickle_enabled;
gboolean janus_ice_is_full_trickle_enabled(void) {
return janus_full_trickle_enabled;
}
/* mDNS resolution support */
static gboolean janus_mdns_enabled;
gboolean janus_ice_is_mdns_enabled(void) {
return janus_mdns_enabled;
}
/* IPv6 support */
static gboolean janus_ipv6_enabled;
gboolean janus_ice_is_ipv6_enabled(void) {
return janus_ipv6_enabled;
}
/* Opaque IDs set by applications are by default only passed to event handlers
* for correlation purposes, but not sent back to the user or application in
* the related Janus API responses or events, unless configured otherwise */
static gboolean opaqueid_in_api = FALSE;
void janus_enable_opaqueid_in_api(void) {
opaqueid_in_api = TRUE;
}
gboolean janus_is_opaqueid_in_api_enabled(void) {
return opaqueid_in_api;
}
/* Only needed in case we're using static event loops spawned at startup (disabled by default) */
typedef struct janus_ice_static_event_loop {
int id;
GMainContext *mainctx;
GMainLoop *mainloop;
GThread *thread;
} janus_ice_static_event_loop;
static int static_event_loops = 0;
static GSList *event_loops = NULL, *current_loop = NULL;
static janus_mutex event_loops_mutex = JANUS_MUTEX_INITIALIZER;
static void *janus_ice_static_event_loop_thread(void *data) {
janus_ice_static_event_loop *loop = data;
JANUS_LOG(LOG_VERB, "[loop#%d] Event loop thread started\n", loop->id);
if(loop->mainloop == NULL) {
JANUS_LOG(LOG_ERR, "[loop#%d] Invalid loop...\n", loop->id);
g_thread_unref(g_thread_self());
return NULL;
}
JANUS_LOG(LOG_DBG, "[loop#%d] Looping...\n", loop->id);
g_main_loop_run(loop->mainloop);
/* When the loop quits, we can unref it */
g_main_loop_unref(loop->mainloop);
g_main_context_unref(loop->mainctx);
JANUS_LOG(LOG_VERB, "[loop#%d] Event loop thread ended!\n", loop->id);
return NULL;
}
int janus_ice_get_static_event_loops(void) {
return static_event_loops;
}
void janus_ice_set_static_event_loops(int loops) {
if(loops == 0)
return;
else if(loops < 1) {
JANUS_LOG(LOG_WARN, "Invalid number of static event loops (%d), disabling\n", loops);
return;
}
/* Create a pool of new event loops */
int i = 0;
for(i=0; i<loops; i++) {
janus_ice_static_event_loop *loop = g_malloc0(sizeof(janus_ice_static_event_loop));
loop->id = static_event_loops;
loop->mainctx = g_main_context_new();
loop->mainloop = g_main_loop_new(loop->mainctx, FALSE);
/* Now spawn a thread for this loop */
GError *error = NULL;
char tname[16];
g_snprintf(tname, sizeof(tname), "hloop %d", loop->id);
loop->thread = g_thread_try_new(tname, &janus_ice_static_event_loop_thread, loop, &error);
if(error != NULL) {
g_main_loop_unref(loop->mainloop);
g_main_context_unref(loop->mainctx);
g_free(loop);
JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch a new event loop thread...\n",
error->code, error->message ? error->message : "??");
g_error_free(error);
} else {
event_loops = g_slist_append(event_loops, loop);
static_event_loops++;
}
}
current_loop = event_loops;
JANUS_LOG(LOG_INFO, "Spawned %d static event loops (handles won't have a dedicated loop)\n", static_event_loops);
return;
}
void janus_ice_stop_static_event_loops(void) {
if(static_event_loops < 1)
return;
/* Quit all the static loops and wait for the threads to leave */
janus_mutex_lock(&event_loops_mutex);
GSList *l = event_loops;
while(l) {
janus_ice_static_event_loop *loop = (janus_ice_static_event_loop *)l->data;
if(loop->mainloop != NULL && g_main_loop_is_running(loop->mainloop))
g_main_loop_quit(loop->mainloop);
g_thread_join(loop->thread);
l = l->next;
}
g_slist_free_full(event_loops, (GDestroyNotify)g_free);
janus_mutex_unlock(&event_loops_mutex);
}
/* libnice debugging */
static gboolean janus_ice_debugging_enabled;
gboolean janus_ice_is_ice_debugging_enabled(void) {
return janus_ice_debugging_enabled;
}
void janus_ice_debugging_enable(void) {
JANUS_LOG(LOG_VERB, "Enabling libnice debugging...\n");
if(g_getenv("NICE_DEBUG") == NULL) {
JANUS_LOG(LOG_WARN, "No NICE_DEBUG environment variable set, setting maximum debug\n");
g_setenv("NICE_DEBUG", "all", TRUE);
}
if(g_getenv("G_MESSAGES_DEBUG") == NULL) {
JANUS_LOG(LOG_WARN, "No G_MESSAGES_DEBUG environment variable set, setting maximum debug\n");
g_setenv("G_MESSAGES_DEBUG", "all", TRUE);
}
JANUS_LOG(LOG_VERB, "Debugging NICE_DEBUG=%s G_MESSAGES_DEBUG=%s\n",
g_getenv("NICE_DEBUG"), g_getenv("G_MESSAGES_DEBUG"));
janus_ice_debugging_enabled = TRUE;
nice_debug_enable(strstr(g_getenv("NICE_DEBUG"), "all") || strstr(g_getenv("NICE_DEBUG"), "stun"));
}
void janus_ice_debugging_disable(void) {
JANUS_LOG(LOG_VERB, "Disabling libnice debugging...\n");
janus_ice_debugging_enabled = FALSE;
nice_debug_disable(TRUE);
}
/* NAT 1:1 stuff */
static gboolean nat_1_1_enabled = FALSE;
static gboolean keep_private_host = FALSE;
void janus_ice_enable_nat_1_1(gboolean kph) {
nat_1_1_enabled = TRUE;
keep_private_host = kph;
}
/* Interface/IP enforce/ignore lists */
GList *janus_ice_enforce_list = NULL, *janus_ice_ignore_list = NULL;
janus_mutex ice_list_mutex;
void janus_ice_enforce_interface(const char *ip) {
if(ip == NULL)
return;
/* Is this an IP or an interface? */
janus_mutex_lock(&ice_list_mutex);
janus_ice_enforce_list = g_list_append(janus_ice_enforce_list, (gpointer)ip);
janus_mutex_unlock(&ice_list_mutex);
}
gboolean janus_ice_is_enforced(const char *ip) {
if(ip == NULL || janus_ice_enforce_list == NULL)
return false;
janus_mutex_lock(&ice_list_mutex);
GList *temp = janus_ice_enforce_list;
while(temp) {
const char *enforced = (const char *)temp->data;
if(enforced != NULL && strstr(ip, enforced) == ip) {
janus_mutex_unlock(&ice_list_mutex);
return true;
}
temp = temp->next;
}
janus_mutex_unlock(&ice_list_mutex);
return false;
}
void janus_ice_ignore_interface(const char *ip) {
if(ip == NULL)
return;
/* Is this an IP or an interface? */
janus_mutex_lock(&ice_list_mutex);
janus_ice_ignore_list = g_list_append(janus_ice_ignore_list, (gpointer)ip);
if(janus_ice_enforce_list != NULL) {
JANUS_LOG(LOG_WARN, "Added %s to the ICE ignore list, but the ICE enforce list is not empty: the ICE ignore list will not be used\n", ip);
}
janus_mutex_unlock(&ice_list_mutex);
}
gboolean janus_ice_is_ignored(const char *ip) {
if(ip == NULL || janus_ice_ignore_list == NULL)
return false;
janus_mutex_lock(&ice_list_mutex);
GList *temp = janus_ice_ignore_list;
while(temp) {
const char *ignored = (const char *)temp->data;
if(ignored != NULL && strstr(ip, ignored) == ip) {
janus_mutex_unlock(&ice_list_mutex);
return true;
}
temp = temp->next;
}
janus_mutex_unlock(&ice_list_mutex);
return false;
}
/* Frequency of statistics via event handlers (one second by default) */
static int janus_ice_event_stats_period = 1;
void janus_ice_set_event_stats_period(int period) {
janus_ice_event_stats_period = period;
}
int janus_ice_get_event_stats_period(void) {
return janus_ice_event_stats_period;
}
/* RTP/RTCP port range */
uint16_t rtp_range_min = 0;
uint16_t rtp_range_max = 0;
#define JANUS_ICE_PACKET_AUDIO 0
#define JANUS_ICE_PACKET_VIDEO 1
#define JANUS_ICE_PACKET_TEXT 2
#define JANUS_ICE_PACKET_BINARY 3
#define JANUS_ICE_PACKET_SCTP 4
/* Janus enqueued (S)RTP/(S)RTCP packet to send */
typedef struct janus_ice_queued_packet {
char *data;
char *label;
char *protocol;
gint length;
gint type;
gboolean control;
gboolean retransmission;
gboolean encrypted;
gint64 added;
} janus_ice_queued_packet;
/* A few static, fake, messages we use as a trigger: e.g., to start a
* new DTLS handshake, hangup a PeerConnection or close a handle */
static janus_ice_queued_packet
janus_ice_start_gathering,
janus_ice_add_candidates,
janus_ice_dtls_handshake,
janus_ice_hangup_peerconnection,
janus_ice_detach_handle,
janus_ice_data_ready;
/* Janus NACKed packet we're tracking (to avoid duplicates) */
typedef struct janus_ice_nacked_packet {
janus_ice_handle *handle;
int vindex;
guint16 seq_number;
guint source_id;
} janus_ice_nacked_packet;
static gboolean janus_ice_nacked_packet_cleanup(gpointer user_data) {
janus_ice_nacked_packet *pkt = (janus_ice_nacked_packet *)user_data;
if(pkt->handle->stream){
JANUS_LOG(LOG_HUGE, "[%"SCNu64"] Cleaning up NACKed packet %"SCNu16" (SSRC %"SCNu32", vindex %d)...\n",
pkt->handle->handle_id, pkt->seq_number, pkt->handle->stream->video_ssrc_peer[pkt->vindex], pkt->vindex);
g_hash_table_remove(pkt->handle->stream->rtx_nacked[pkt->vindex], GUINT_TO_POINTER(pkt->seq_number));
g_hash_table_remove(pkt->handle->stream->pending_nacked_cleanup, GUINT_TO_POINTER(pkt->source_id));
}
return G_SOURCE_REMOVE;
}
/* Deallocation helpers for handles and related structs */
static void janus_ice_handle_free(const janus_refcount *handle_ref);
static void janus_ice_webrtc_free(janus_ice_handle *handle);
static void janus_ice_plugin_session_free(const janus_refcount *app_handle_ref);
static void janus_ice_stream_free(const janus_refcount *handle_ref);
static void janus_ice_component_free(const janus_refcount *handle_ref);
/* Custom GSource for outgoing traffic */
typedef struct janus_ice_outgoing_traffic {
GSource parent;
janus_ice_handle *handle;
GDestroyNotify destroy;
} janus_ice_outgoing_traffic;
static gboolean janus_ice_outgoing_rtcp_handle(gpointer user_data);
static gboolean janus_ice_outgoing_stats_handle(gpointer user_data);
static gboolean janus_ice_outgoing_traffic_handle(janus_ice_handle *handle, janus_ice_queued_packet *pkt);
static gboolean janus_ice_outgoing_traffic_prepare(GSource *source, gint *timeout) {
janus_ice_outgoing_traffic *t = (janus_ice_outgoing_traffic *)source;
return (g_async_queue_length(t->handle->queued_packets) > 0);
}
static gboolean janus_ice_outgoing_traffic_dispatch(GSource *source, GSourceFunc callback, gpointer user_data) {
janus_ice_outgoing_traffic *t = (janus_ice_outgoing_traffic *)source;
int ret = G_SOURCE_CONTINUE;
janus_ice_queued_packet *pkt = NULL;
while((pkt = g_async_queue_try_pop(t->handle->queued_packets)) != NULL) {
if(janus_ice_outgoing_traffic_handle(t->handle, pkt) == G_SOURCE_REMOVE)
ret = G_SOURCE_REMOVE;
}
return ret;
}
static void janus_ice_outgoing_traffic_finalize(GSource *source) {
janus_ice_outgoing_traffic *t = (janus_ice_outgoing_traffic *)source;
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Finalizing loop source\n", t->handle->handle_id);
if(static_event_loops > 0) {
/* This handle was sharing an event loop with others */
janus_ice_webrtc_free(t->handle);
janus_refcount_decrease(&t->handle->ref);
} else if(t->handle->mainloop != NULL && g_main_loop_is_running(t->handle->mainloop)) {
/* This handle had a dedicated event loop, quit it */
g_main_loop_quit(t->handle->mainloop);
}
janus_refcount_decrease(&t->handle->ref);
}
static GSourceFuncs janus_ice_outgoing_traffic_funcs = {
janus_ice_outgoing_traffic_prepare,
NULL, /* We don't need check */
janus_ice_outgoing_traffic_dispatch,
janus_ice_outgoing_traffic_finalize,
NULL, NULL
};
static GSource *janus_ice_outgoing_traffic_create(janus_ice_handle *handle, GDestroyNotify destroy) {
GSource *source = g_source_new(&janus_ice_outgoing_traffic_funcs, sizeof(janus_ice_outgoing_traffic));
janus_ice_outgoing_traffic *t = (janus_ice_outgoing_traffic *)source;
char name[255];
g_snprintf(name, sizeof(name), "source-%"SCNu64, handle->handle_id);
g_source_set_name(source, name);
janus_refcount_increase(&handle->ref);
t->handle = handle;
t->destroy = destroy;
return source;
}
/* Time, in seconds, that should pass with no media (audio or video) being
* received before Janus notifies you about this with a receiving=false */
#define DEFAULT_NO_MEDIA_TIMER 1
static uint no_media_timer = DEFAULT_NO_MEDIA_TIMER;
void janus_set_no_media_timer(uint timer) {
no_media_timer = timer;
if(no_media_timer == 0)
JANUS_LOG(LOG_VERB, "Disabling no-media timer\n");
else
JANUS_LOG(LOG_VERB, "Setting no-media timer to %us\n", no_media_timer);
}
uint janus_get_no_media_timer(void) {
return no_media_timer;
}
/* Number of lost packets per seconds on a media stream (uplink or downlink,
* audio or video), that should result in a slow-link event to the iser */
#define DEFAULT_SLOWLINK_THRESHOLD 4
static uint slowlink_threshold = DEFAULT_SLOWLINK_THRESHOLD;
void janus_set_slowlink_threshold(uint packets) {
slowlink_threshold = packets;
if(slowlink_threshold == 0)
JANUS_LOG(LOG_VERB, "Disabling slow-link events\n");
else
JANUS_LOG(LOG_VERB, "Setting slowlink-threshold to %u packets\n", slowlink_threshold);
}
uint janus_get_slowlink_threshold(void) {
return slowlink_threshold;
}
/* Period, in milliseconds, to refer to for sending TWCC feedback */
#define DEFAULT_TWCC_PERIOD 200
static uint twcc_period = DEFAULT_TWCC_PERIOD;
void janus_set_twcc_period(uint period) {
twcc_period = period;
if(twcc_period == 0) {
JANUS_LOG(LOG_WARN, "Invalid TWCC period, falling back to default\n");
twcc_period = DEFAULT_TWCC_PERIOD;
} else {
JANUS_LOG(LOG_VERB, "Setting TWCC period to %ds\n", twcc_period);
}
}
uint janus_get_twcc_period(void) {
return twcc_period;
}
/* DSCP value, which we can set via libnice: it's disabled by default */
static int dscp_ef = 0;
void janus_set_dscp(int dscp) {
dscp_ef = dscp;
if(dscp_ef > 0) {
JANUS_LOG(LOG_VERB, "Setting DSCP EF to %d\n", dscp_ef);
}
}
int janus_get_dscp(void) {
return dscp_ef;
}
static inline void janus_ice_free_rtp_packet(janus_rtp_packet *pkt) {
if(pkt == NULL) {
return;
}
g_free(pkt->data);
g_free(pkt);
}
static void janus_ice_free_queued_packet(janus_ice_queued_packet *pkt) {
if(pkt == NULL || pkt == &janus_ice_start_gathering ||
pkt == &janus_ice_add_candidates ||
pkt == &janus_ice_dtls_handshake ||
pkt == &janus_ice_hangup_peerconnection ||
pkt == &janus_ice_detach_handle ||
pkt == &janus_ice_data_ready) {
return;
}
g_free(pkt->data);
g_free(pkt->label);
g_free(pkt->protocol);
g_free(pkt);
}
/* Minimum and maximum value, in milliseconds, for the NACK queue/retransmissions (default=200ms/1000ms) */
#define DEFAULT_MIN_NACK_QUEUE 200
#define DEFAULT_MAX_NACK_QUEUE 1000
/* Maximum ignore count after retransmission (200ms) */
#define MAX_NACK_IGNORE 200000
static gboolean nack_optimizations = FALSE;
void janus_set_nack_optimizations_enabled(gboolean optimize) {
nack_optimizations = optimize;
}
gboolean janus_is_nack_optimizations_enabled(void) {
return nack_optimizations;
}
static uint16_t min_nack_queue = DEFAULT_MIN_NACK_QUEUE;
void janus_set_min_nack_queue(uint16_t mnq) {
min_nack_queue = mnq < DEFAULT_MAX_NACK_QUEUE ? mnq : DEFAULT_MAX_NACK_QUEUE;
if(min_nack_queue == 0)
JANUS_LOG(LOG_VERB, "Disabling NACK queue\n");
else
JANUS_LOG(LOG_VERB, "Setting min NACK queue to %dms\n", min_nack_queue);
}
uint16_t janus_get_min_nack_queue(void) {
return min_nack_queue;
}
/* Helper to clean old NACK packets in the buffer when they exceed the queue time limit */
static void janus_cleanup_nack_buffer(gint64 now, janus_ice_stream *stream, gboolean audio, gboolean video) {
if(stream && stream->component) {
janus_ice_component *component = stream->component;
if(audio && component->audio_retransmit_buffer) {
janus_rtp_packet *p = (janus_rtp_packet *)g_queue_peek_head(component->audio_retransmit_buffer);
while(p && (!now || (now - p->created >= (gint64)stream->nack_queue_ms*1000))) {
/* Packet is too old, get rid of it */
g_queue_pop_head(component->audio_retransmit_buffer);
/* Remove from hashtable too */
janus_rtp_header *header = (janus_rtp_header *)p->data;
guint16 seq = ntohs(header->seq_number);
g_hash_table_remove(component->audio_retransmit_seqs, GUINT_TO_POINTER(seq));
/* Free the packet */
janus_ice_free_rtp_packet(p);
p = (janus_rtp_packet *)g_queue_peek_head(component->audio_retransmit_buffer);
}
}
if(video && component->video_retransmit_buffer) {
janus_rtp_packet *p = (janus_rtp_packet *)g_queue_peek_head(component->video_retransmit_buffer);
while(p && (!now || (now - p->created >= (gint64)stream->nack_queue_ms*1000))) {
/* Packet is too old, get rid of it */
g_queue_pop_head(component->video_retransmit_buffer);
/* Remove from hashtable too */
janus_rtp_header *header = (janus_rtp_header *)p->data;
guint16 seq = ntohs(header->seq_number);
g_hash_table_remove(component->video_retransmit_seqs, GUINT_TO_POINTER(seq));
/* Free the packet */
janus_ice_free_rtp_packet(p);
p = (janus_rtp_packet *)g_queue_peek_head(component->video_retransmit_buffer);
}
}
}
}
#define SEQ_MISSING_WAIT 12000 /* 12ms */
#define SEQ_NACKED_WAIT 155000 /* 155ms */
/* janus_seq_info list functions */
static void janus_seq_append(janus_seq_info **head, janus_seq_info *new_seq) {
if(*head == NULL) {
new_seq->prev = new_seq;
new_seq->next = new_seq;
*head = new_seq;
} else {
janus_seq_info *last_seq = (*head)->prev;
new_seq->prev = last_seq;
new_seq->next = *head;
(*head)->prev = new_seq;
last_seq->next = new_seq;
}
}
static janus_seq_info *janus_seq_pop_head(janus_seq_info **head) {
janus_seq_info *pop_seq = *head;
if(pop_seq) {
janus_seq_info *new_head = pop_seq->next;
if(pop_seq == new_head || new_head == NULL) {
*head = NULL;
} else {
*head = new_head;
new_head->prev = pop_seq->prev;
new_head->prev->next = new_head;
}
}
return pop_seq;
}
void janus_seq_list_free(janus_seq_info **head) {
if(!*head)
return;
janus_seq_info *cur = *head;
do {
janus_seq_info *next = cur->next;
g_free(cur);
cur = next;
} while(cur != *head);
*head = NULL;
}
static int janus_seq_in_range(guint16 seqn, guint16 start, guint16 len) {
/* Supports wrapping sequence (easier with int range) */
int n = seqn;
int nh = (1<<16) + n;
int s = start;
int e = s + len;
return (s <= n && n < e) || (s <= nh && nh < e);
}
/* Internal method for relaying RTCP messages, optionally filtering them in case they come from plugins */
void janus_ice_relay_rtcp_internal(janus_ice_handle *handle, janus_plugin_rtcp *packet, gboolean filter_rtcp);
/* Map of active plugin sessions */
static GHashTable *plugin_sessions;
static janus_mutex plugin_sessions_mutex;
gboolean janus_plugin_session_is_alive(janus_plugin_session *plugin_session) {
if(plugin_session == NULL || plugin_session < (janus_plugin_session *)0x1000 ||
g_atomic_int_get(&plugin_session->stopped))
return FALSE;
/* Make sure this plugin session is still alive */
janus_mutex_lock_nodebug(&plugin_sessions_mutex);
janus_plugin_session *result = g_hash_table_lookup(plugin_sessions, plugin_session);
janus_mutex_unlock_nodebug(&plugin_sessions_mutex);
if(result == NULL) {
JANUS_LOG(LOG_ERR, "Invalid plugin session (%p)\n", plugin_session);
}
return (result != NULL);
}
static void janus_plugin_session_dereference(janus_plugin_session *plugin_session) {
if(plugin_session)
janus_refcount_decrease(&plugin_session->ref);
}
static void janus_ice_clear_queued_candidates(janus_ice_handle *handle) {
if(handle == NULL || handle->queued_candidates == NULL) {
return;
}
while(g_async_queue_length(handle->queued_candidates) > 0) {
(void)g_async_queue_try_pop(handle->queued_candidates);
}
}
static void janus_ice_clear_queued_packets(janus_ice_handle *handle) {
if(handle == NULL || handle->queued_packets == NULL) {
return;
}
janus_ice_queued_packet *pkt = NULL;
while(g_async_queue_length(handle->queued_packets) > 0) {
pkt = g_async_queue_try_pop(handle->queued_packets);
janus_ice_free_queued_packet(pkt);
}
}
static void janus_ice_notify_trickle(janus_ice_handle *handle, char *buffer) {
if(handle == NULL)
return;
char cbuffer[200];
if(buffer != NULL)
g_snprintf(cbuffer, sizeof(cbuffer), "candidate:%s", buffer);
/* Send a "trickle" event to the browser */
janus_session *session = (janus_session *)handle->session;
if(session == NULL)
return;
json_t *event = json_object();
json_object_set_new(event, "janus", json_string("trickle"));
json_object_set_new(event, "session_id", json_integer(session->session_id));
json_object_set_new(event, "sender", json_integer(handle->handle_id));
if(opaqueid_in_api && handle->opaque_id != NULL)
json_object_set_new(event, "opaque_id", json_string(handle->opaque_id));
json_t *candidate = json_object();
if(buffer != NULL) {
json_object_set_new(candidate, "sdpMid", json_string(handle->stream_mid));
json_object_set_new(candidate, "sdpMLineIndex", json_integer(0));
json_object_set_new(candidate, "candidate", json_string(cbuffer));
} else {
json_object_set_new(candidate, "completed", json_true());
}
json_object_set_new(event, "candidate", candidate);
/* Send the event */
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Sending trickle event (%s) to transport...\n",
handle->handle_id, buffer ? "candidate" : "end-of-candidates");
janus_session_notify_event(session, event);
}
static void janus_ice_notify_media(janus_ice_handle *handle, gboolean video, gboolean up) {
if(handle == NULL)
return;
/* Prepare JSON event to notify user/application */
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Notifying that we %s receiving %s\n",
handle->handle_id, up ? "are" : "are NOT", video ? "video" : "audio");
janus_session *session = (janus_session *)handle->session;
if(session == NULL)
return;
json_t *event = json_object();
json_object_set_new(event, "janus", json_string("media"));
json_object_set_new(event, "session_id", json_integer(session->session_id));
json_object_set_new(event, "sender", json_integer(handle->handle_id));
if(opaqueid_in_api && handle->opaque_id != NULL)
json_object_set_new(event, "opaque_id", json_string(handle->opaque_id));
json_object_set_new(event, "type", json_string(video ? "video" : "audio"));
json_object_set_new(event, "receiving", up ? json_true() : json_false());
if(!up && no_media_timer > 1)
json_object_set_new(event, "seconds", json_integer(no_media_timer));
/* Send the event */
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Sending event to transport...\n", handle->handle_id);
janus_session_notify_event(session, event);
/* Notify event handlers as well */
if(janus_events_is_enabled()) {
json_t *info = json_object();
json_object_set_new(info, "media", json_string(video ? "video" : "audio"));
json_object_set_new(info, "receiving", up ? json_true() : json_false());
if(!up && no_media_timer > 1)
json_object_set_new(info, "seconds", json_integer(no_media_timer));
janus_events_notify_handlers(JANUS_EVENT_TYPE_MEDIA, JANUS_EVENT_SUBTYPE_MEDIA_STATE,
session->session_id, handle->handle_id, handle->opaque_id, info);
}
}
void janus_ice_notify_hangup(janus_ice_handle *handle, const char *reason) {
if(handle == NULL)
return;
/* Prepare JSON event to notify user/application */
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Notifying WebRTC hangup; %p\n", handle->handle_id, handle);
janus_session *session = (janus_session *)handle->session;
if(session == NULL)
return;
json_t *event = json_object();
json_object_set_new(event, "janus", json_string("hangup"));
json_object_set_new(event, "session_id", json_integer(session->session_id));
json_object_set_new(event, "sender", json_integer(handle->handle_id));
if(opaqueid_in_api && handle->opaque_id != NULL)
json_object_set_new(event, "opaque_id", json_string(handle->opaque_id));
if(reason != NULL)
json_object_set_new(event, "reason", json_string(reason));
/* Send the event */
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Sending event to transport...; %p\n", handle->handle_id, handle);
janus_session_notify_event(session, event);
/* Notify event handlers as well */
if(janus_events_is_enabled()) {
json_t *info = json_object();
json_object_set_new(info, "connection", json_string("hangup"));
if(reason != NULL)
json_object_set_new(info, "reason", json_string(reason));
janus_events_notify_handlers(JANUS_EVENT_TYPE_WEBRTC, JANUS_EVENT_SUBTYPE_WEBRTC_STATE,
session->session_id, handle->handle_id, handle->opaque_id, info);
}
}
/* Trickle helpers */
janus_ice_trickle *janus_ice_trickle_new(const char *transaction, json_t *candidate) {
if(transaction == NULL || candidate == NULL)
return NULL;
janus_ice_trickle *trickle = g_malloc(sizeof(janus_ice_trickle));
trickle->handle = NULL;
trickle->received = janus_get_monotonic_time();
trickle->transaction = g_strdup(transaction);
trickle->candidate = json_deep_copy(candidate);
return trickle;
}
gint janus_ice_trickle_parse(janus_ice_handle *handle, json_t *candidate, const char **error) {
const char *ignore_error = NULL;
if(error == NULL) {
error = &ignore_error;
}
if(handle == NULL) {
*error = "Invalid handle";
return JANUS_ERROR_HANDLE_NOT_FOUND;
}
/* Parse trickle candidate */
if(!json_is_object(candidate) || json_object_get(candidate, "completed") != NULL) {
JANUS_LOG(LOG_VERB, "No more remote candidates for handle %"SCNu64"!\n", handle->handle_id);
janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALL_TRICKLES);
} else {
/* Handle remote candidate */
json_t *mid = json_object_get(candidate, "sdpMid");
if(mid && !json_is_string(mid)) {
*error = "Trickle error: invalid element type (sdpMid should be a string)";
return JANUS_ERROR_INVALID_ELEMENT_TYPE;
}
json_t *mline = json_object_get(candidate, "sdpMLineIndex");
if(mline && (!json_is_integer(mline) || json_integer_value(mline) < 0)) {
*error = "Trickle error: invalid element type (sdpMLineIndex should be a positive integer)";
return JANUS_ERROR_INVALID_ELEMENT_TYPE;
}
if(!mid && !mline) {
*error = "Trickle error: missing mandatory element (sdpMid or sdpMLineIndex)";
return JANUS_ERROR_MISSING_MANDATORY_ELEMENT;
}
json_t *rc = json_object_get(candidate, "candidate");
if(!rc) {
*error = "Trickle error: missing mandatory element (candidate)";
return JANUS_ERROR_MISSING_MANDATORY_ELEMENT;
}
if(!json_is_string(rc)) {
*error = "Trickle error: invalid element type (candidate should be a string)";
return JANUS_ERROR_INVALID_ELEMENT_TYPE;
}
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Trickle candidate (%s): %s\n", handle->handle_id, json_string_value(mid), json_string_value(rc));
/* Parse it */
int sdpMLineIndex = mline ? json_integer_value(mline) : -1;
const char *sdpMid = json_string_value(mid);
if(sdpMLineIndex > 0 || (handle->stream_mid && sdpMid && strcmp(handle->stream_mid, sdpMid))) {
/* FIXME We bundle everything, so we ignore candidates for anything beyond the first m-line */
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Got a mid='%s' candidate (index %d) but we're bundling, ignoring...\n",
handle->handle_id, json_string_value(mid), sdpMLineIndex);
return 0;
}
janus_ice_stream *stream = handle->stream;
if(stream == NULL) {
*error = "Trickle error: invalid element type (no such stream)";
return JANUS_ERROR_TRICKE_INVALID_STREAM;
}
int res = janus_sdp_parse_candidate(stream, json_string_value(rc), 1);
if(res != 0) {
JANUS_LOG(LOG_ERR, "[%"SCNu64"] Failed to parse candidate... (%d)\n", handle->handle_id, res);
/* FIXME Should we return an error? */
}
}
return 0;
}
void janus_ice_trickle_destroy(janus_ice_trickle *trickle) {
if(trickle == NULL)
return;
g_free(trickle->transaction);
trickle->transaction = NULL;
if(trickle->candidate)
json_decref(trickle->candidate);
trickle->candidate = NULL;
g_free(trickle);
}
/* libnice initialization */
void janus_ice_init(gboolean ice_lite, gboolean ice_tcp, gboolean full_trickle, gboolean ignore_mdns,
gboolean ipv6, uint16_t rtp_min_port, uint16_t rtp_max_port) {
janus_ice_lite_enabled = ice_lite;
janus_ice_tcp_enabled = ice_tcp;
janus_full_trickle_enabled = full_trickle;
janus_mdns_enabled = !ignore_mdns;
janus_ipv6_enabled = ipv6;
JANUS_LOG(LOG_INFO, "Initializing ICE stuff (%s mode, ICE-TCP candidates %s, %s-trickle, IPv6 support %s)\n",
janus_ice_lite_enabled ? "Lite" : "Full",
janus_ice_tcp_enabled ? "enabled" : "disabled",
janus_full_trickle_enabled ? "full" : "half",
janus_ipv6_enabled ? "enabled" : "disabled");
if(janus_ice_tcp_enabled) {
#ifndef HAVE_LIBNICE_TCP
JANUS_LOG(LOG_WARN, "libnice version < 0.1.8, disabling ICE-TCP support\n");
janus_ice_tcp_enabled = FALSE;
#else
if(!janus_ice_lite_enabled) {
JANUS_LOG(LOG_WARN, "You may experience problems when having ICE-TCP enabled without having ICE Lite enabled too in libnice\n");
}
#endif
}
/* libnice debugging is disabled unless explicitly stated */
nice_debug_disable(TRUE);
/*! \note The RTP/RTCP port range configuration may be just a placeholder: for
* instance, libnice supports this since 0.1.0, but the 0.1.3 on Fedora fails
* when linking with an undefined reference to \c nice_agent_set_port_range
* so this is checked by the install.sh script in advance. */
rtp_range_min = rtp_min_port;
rtp_range_max = rtp_max_port;
if(rtp_range_max < rtp_range_min) {
JANUS_LOG(LOG_WARN, "Invalid ICE port range: %"SCNu16" > %"SCNu16"\n", rtp_range_min, rtp_range_max);
} else if(rtp_range_min > 0 || rtp_range_max > 0) {
#ifndef HAVE_PORTRANGE
JANUS_LOG(LOG_WARN, "nice_agent_set_port_range unavailable, port range disabled\n");
#else
JANUS_LOG(LOG_INFO, "ICE port range: %"SCNu16"-%"SCNu16"\n", rtp_range_min, rtp_range_max);
#endif
}
if(!janus_mdns_enabled)
JANUS_LOG(LOG_WARN, "mDNS resolution disabled, .local candidates will be ignored\n");
/* We keep track of plugin sessions to avoid problems */
plugin_sessions = g_hash_table_new_full(NULL, NULL, NULL, (GDestroyNotify)janus_plugin_session_dereference);
janus_mutex_init(&plugin_sessions_mutex);
#ifdef HAVE_TURNRESTAPI
/* Initialize the TURN REST API client stack, whether we're going to use it or not */
janus_turnrest_init();
#endif
}
void janus_ice_deinit(void) {
#ifdef HAVE_TURNRESTAPI
janus_turnrest_deinit();
#endif
}
int janus_ice_test_stun_server(janus_network_address *addr, uint16_t port,
uint16_t local_port, janus_network_address *public_addr, uint16_t *public_port) {
if(!addr || !public_addr)
return -1;
/* Test the STUN server */
StunAgent stun;
stun_agent_init (&stun, STUN_ALL_KNOWN_ATTRIBUTES, STUN_COMPATIBILITY_RFC5389, 0);
StunMessage msg;
uint8_t buf[1500];
size_t len = stun_usage_bind_create(&stun, &msg, buf, 1500);
JANUS_LOG(LOG_INFO, "Testing STUN server: message is of %zu bytes\n", len);
/* Use the janus_network_address info to drive the socket creation */
int fd = socket(addr->family, SOCK_DGRAM, 0);
if(fd < 0) {
JANUS_LOG(LOG_FATAL, "Error creating socket for STUN BINDING test\n");
return -1;
}
struct sockaddr *address = NULL, *remote = NULL;
struct sockaddr_in address4 = { 0 }, remote4 = { 0 };
struct sockaddr_in6 address6 = { 0 }, remote6 = { 0 };
socklen_t addrlen = 0;
if(addr->family == AF_INET) {
memset(&address4, 0, sizeof(address4));
address4.sin_family = AF_INET;
address4.sin_port = htons(local_port);
address4.sin_addr.s_addr = INADDR_ANY;
memset(&remote4, 0, sizeof(remote4));
remote4.sin_family = AF_INET;
remote4.sin_port = htons(port);
memcpy(&remote4.sin_addr, &addr->ipv4, sizeof(addr->ipv4));
address = (struct sockaddr *)(&address4);
remote = (struct sockaddr *)(&remote4);
addrlen = sizeof(remote4);
} else if(addr->family == AF_INET6) {
memset(&address6, 0, sizeof(address6));
address6.sin6_family = AF_INET6;
address6.sin6_port = htons(local_port);
address6.sin6_addr = in6addr_any;
memset(&remote6, 0, sizeof(remote6));
remote6.sin6_family = AF_INET6;
remote6.sin6_port = htons(port);
memcpy(&remote6.sin6_addr, &addr->ipv6, sizeof(addr->ipv6));
remote6.sin6_addr = addr->ipv6;
address = (struct sockaddr *)(&address6);
remote = (struct sockaddr *)(&remote6);
addrlen = sizeof(remote6);
}
if(bind(fd, address, addrlen) < 0) {
JANUS_LOG(LOG_FATAL, "Bind failed for STUN BINDING test: %d (%s)\n", errno, strerror(errno));
close(fd);
return -1;
}
int bytes = sendto(fd, buf, len, 0, remote, addrlen);
if(bytes < 0) {
JANUS_LOG(LOG_FATAL, "Error sending STUN BINDING test\n");
close(fd);
return -1;
}
JANUS_LOG(LOG_VERB, " >> Sent %d bytes, waiting for reply...\n", bytes);
struct timeval timeout;
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(fd, &readfds);
timeout.tv_sec = 5; /* FIXME Don't wait forever */
timeout.tv_usec = 0;
int err = select(fd+1, &readfds, NULL, NULL, &timeout);
if(err < 0) {
JANUS_LOG(LOG_FATAL, "Error waiting for a response to our STUN BINDING test: %d (%s)\n", errno, strerror(errno));
close(fd);
return -1;
}
if(!FD_ISSET(fd, &readfds)) {
JANUS_LOG(LOG_FATAL, "No response to our STUN BINDING test\n");
close(fd);
return -1;
}
bytes = recvfrom(fd, buf, 1500, 0, remote, &addrlen);
JANUS_LOG(LOG_VERB, " >> Got %d bytes...\n", bytes);
close(fd);
if(bytes < 0) {
JANUS_LOG(LOG_FATAL, "Failed to receive STUN\n");
return -1;
}
if(stun_agent_validate (&stun, &msg, buf, bytes, NULL, NULL) != STUN_VALIDATION_SUCCESS) {
JANUS_LOG(LOG_FATAL, "Failed to validate STUN BINDING response\n");
return -1;
}
StunClass class = stun_message_get_class(&msg);
StunMethod method = stun_message_get_method(&msg);
if(class != STUN_RESPONSE || method != STUN_BINDING) {
JANUS_LOG(LOG_FATAL, "Unexpected STUN response: %d/%d\n", class, method);
return -1;
}
StunMessageReturn ret = stun_message_find_xor_addr(&msg, STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS, (struct sockaddr_storage *)address, &addrlen);
JANUS_LOG(LOG_VERB, " >> XOR-MAPPED-ADDRESS: %d\n", ret);
if(ret == STUN_MESSAGE_RETURN_SUCCESS) {
if(janus_network_address_from_sockaddr(address, public_addr) != 0) {
JANUS_LOG(LOG_ERR, "Could not resolve XOR-MAPPED-ADDRESS...\n");
return -1;
}
if(public_port != NULL) {
if(address->sa_family == AF_INET) {
struct sockaddr_in *addr = (struct sockaddr_in *)address;