forked from meetecho/janus-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ice.c
3394 lines (3280 loc) · 133 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 gateway callbacks instead.
*
* \ingroup protocols
* \ref protocols
*/
#include <ifaddrs.h>
#include <net/if.h>
#include <sys/socket.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 "dtls.h"
#include "sdp.h"
#include "rtp.h"
#include "rtcp.h"
#include "apierror.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_LIBCURL
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;
}
/* IPv6 support (still mostly WIP) */
static gboolean janus_ipv6_enabled;
gboolean janus_ice_is_ipv6_enabled(void) {
return janus_ipv6_enabled;
}
/* Whether BUNDLE support is mandatory or not (false by default) */
static gboolean janus_force_bundle;
void janus_ice_force_bundle(gboolean forced) {
janus_force_bundle = forced;
JANUS_LOG(LOG_INFO, "BUNDLE %s going to be forced\n", janus_force_bundle ? "is" : "is NOT");
}
gboolean janus_ice_is_bundle_forced(void) {
return janus_force_bundle;
}
/* Whether rtcp-mux support is mandatory or not (false by default) */
static gboolean janus_force_rtcpmux;
static gint janus_force_rtcpmux_blackhole_port = 1234;
static gint janus_force_rtcpmux_blackhole_fd = 0;
void janus_ice_force_rtcpmux(gboolean forced) {
janus_force_rtcpmux = forced;
JANUS_LOG(LOG_INFO, "rtcp-mux %s going to be forced\n", janus_force_rtcpmux ? "is" : "is NOT");
if(!janus_force_rtcpmux) {
/*
* Since rtcp-mux is NOT going to be forced, we need to do some magic to get rid of unneeded
* RTCP components when rtcp-mux is indeed negotiated when creating a PeerConnection. In
* particular, there's no way to remove a component in libnice (you can only remove streams),
* and you can read why this is a problem here:
* https://github.com/meetecho/janus-gateway/issues/154
* https://github.com/meetecho/janus-gateway/pull/362
* This means that, to effectively do that without just ignoring the component, we need
* to set a dummy candidate on it to "trick" libnice into thinking ICE is done for it.
* Since libnice will still occasionally send keepalives to the dummy peer, and we don't
* want it to send messages to a service that might not like it, we create a "blackhole"
* UDP server to receive all those keepalives and then just discard them.
*/
int blackhole = socket(AF_INET, SOCK_DGRAM, 0);
if(blackhole < 0) {
JANUS_LOG(LOG_WARN, "Error creating RTCP component blackhole socket, using port %d instead\n", janus_force_rtcpmux_blackhole_port);
return;
}
fcntl(blackhole, F_SETFL, O_NONBLOCK);
struct sockaddr_in serveraddr;
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(0); /* Choose a random port, that works for us */
if(bind(blackhole, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) {
JANUS_LOG(LOG_WARN, "Error binding RTCP component blackhole socket, using port %d instead\n", janus_force_rtcpmux_blackhole_port);
return;
}
socklen_t len = sizeof(serveraddr);
if(getsockname(blackhole, (struct sockaddr *)&serveraddr, &len) < 0) {
JANUS_LOG(LOG_WARN, "Error retrieving port assigned to RTCP component blackhole socket, using port %d instead\n", janus_force_rtcpmux_blackhole_port);
return;
}
janus_force_rtcpmux_blackhole_port = ntohs(serveraddr.sin_port);
JANUS_LOG(LOG_VERB, " -- RTCP component blackhole socket bound to port %d\n", janus_force_rtcpmux_blackhole_port);
janus_force_rtcpmux_blackhole_fd = blackhole;
}
}
gint janus_ice_get_rtcpmux_blackhole_port(void) {
return janus_force_rtcpmux_blackhole_port;
}
gboolean janus_ice_is_rtcpmux_forced(void) {
return janus_force_rtcpmux;
}
/* 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;
void janus_ice_enable_nat_1_1(void) {
nat_1_1_enabled = TRUE;
}
/* 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)) {
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)) {
janus_mutex_unlock(&ice_list_mutex);
return true;
}
temp = temp->next;
}
janus_mutex_unlock(&ice_list_mutex);
return false;
}
/* RTP/RTCP port range */
uint16_t rtp_range_min = 0;
uint16_t rtp_range_max = 0;
/* Helpers to demultiplex protocols */
gboolean janus_is_dtls(gchar *buf);
gboolean janus_is_dtls(gchar *buf) {
return ((*buf >= 20) && (*buf <= 64));
}
gboolean janus_is_rtp(gchar *buf);
gboolean janus_is_rtp(gchar *buf) {
rtp_header *header = (rtp_header *)buf;
return ((header->type < 64) || (header->type >= 96));
}
gboolean janus_is_rtcp(gchar *buf);
gboolean janus_is_rtcp(gchar *buf) {
rtp_header *header = (rtp_header *)buf;
return ((header->type >= 64) && (header->type < 96));
}
#define JANUS_ICE_PACKET_AUDIO 0
#define JANUS_ICE_PACKET_VIDEO 1
#define JANUS_ICE_PACKET_DATA 2
/* Janus enqueued (S)RTP/(S)RTCP packet to send */
typedef struct janus_ice_queued_packet {
char *data;
gint length;
gint type;
gboolean control;
gboolean encrypted;
} janus_ice_queued_packet;
/* This is a static, fake, message we use as a trigger to send a DTLS alert */
static janus_ice_queued_packet janus_ice_dtls_alert;
/* Maximum values for the NACK queue/retransmissions */
#define DEFAULT_MAX_NACK_QUEUE 300
/* Maximum ignore count after retransmission (100ms) */
#define MAX_NACK_IGNORE 100000
static uint max_nack_queue = DEFAULT_MAX_NACK_QUEUE;
void janus_set_max_nack_queue(uint mnq) {
max_nack_queue = mnq;
JANUS_LOG(LOG_VERB, "Setting max NACK queue to %d\n", max_nack_queue);
}
uint janus_get_max_nack_queue(void) {
return max_nack_queue;
}
#define SEQ_MISSING_WAIT 12000 /* 12ms */
#define SEQ_NACKED_WAIT 155000 /* 155ms */
/* seq_info_t list functions */
static void janus_seq_append(seq_info_t **head, seq_info_t *new_seq) {
if(*head == NULL) {
new_seq->prev = new_seq;
new_seq->next = new_seq;
*head = new_seq;
} else {
seq_info_t *last_seq = (*head)->prev;
new_seq->prev = last_seq;
new_seq->next = *head;
(*head)->prev = new_seq;
last_seq->next = new_seq;
}
}
static seq_info_t *janus_seq_pop_head(seq_info_t **head) {
seq_info_t *pop_seq = *head;
if(pop_seq) {
seq_info_t *new_head = pop_seq->next;
if (pop_seq == new_head) {
*head = NULL;
} else {
*head = new_head;
new_head->prev = pop_seq->prev;
new_head->prev->next = new_head;
}
}
return pop_seq;
}
static void janus_seq_list_free(seq_info_t **head) {
if(!*head) return;
seq_info_t *cur = *head;
do {
seq_info_t *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);
}
/* Map of old plugin sessions that have been closed */
static GHashTable *old_plugin_sessions;
static janus_mutex old_plugin_sessions_mutex;
gboolean janus_plugin_session_is_alive(janus_plugin_session *plugin_session) {
/* Make sure this plugin session is still alive */
janus_mutex_lock(&old_plugin_sessions_mutex);
janus_plugin_session *result = g_hash_table_lookup(old_plugin_sessions, plugin_session);
janus_mutex_unlock(&old_plugin_sessions_mutex);
if(result != NULL) {
JANUS_LOG(LOG_ERR, "Invalid plugin session (%p)\n", plugin_session);
}
return (result == NULL);
}
/* Watchdog for removing old handles */
static GHashTable *old_handles = NULL;
static GMainContext *handles_watchdog_context = NULL;
GMainLoop *handles_watchdog_loop = NULL;
GThread *handles_watchdog = NULL;
static janus_mutex old_handles_mutex;
static gboolean janus_ice_handles_cleanup(gpointer user_data) {
janus_ice_handle *handle = (janus_ice_handle *) user_data;
JANUS_LOG(LOG_INFO, "Cleaning up handle %"SCNu64"...\n", handle->handle_id);
janus_ice_free(handle);
return G_SOURCE_REMOVE;
}
static gboolean janus_ice_handles_check(gpointer user_data) {
GMainContext *watchdog_context = (GMainContext *) user_data;
janus_mutex_lock(&old_handles_mutex);
if(old_handles && g_hash_table_size(old_handles) > 0) {
GHashTableIter iter;
gpointer value;
g_hash_table_iter_init(&iter, old_handles);
while (g_hash_table_iter_next(&iter, NULL, &value)) {
janus_ice_handle *handle = (janus_ice_handle *) value;
if (!handle) {
continue;
}
/* Schedule the ICE handle for deletion */
g_hash_table_iter_remove(&iter);
GSource *timeout_source = g_timeout_source_new_seconds(3);
g_source_set_callback(timeout_source, janus_ice_handles_cleanup, handle, NULL);
g_source_attach(timeout_source, watchdog_context);
g_source_unref(timeout_source);
}
}
janus_mutex_unlock(&old_handles_mutex);
if(janus_force_rtcpmux_blackhole_fd > 0) {
/* Also read the blackhole socket (unneeded RTCP components keepalives) and dump the packets */
char buffer[1500];
struct sockaddr_storage addr;
socklen_t len = sizeof(addr);
ssize_t res = 0;
do {
/* Read and ignore */
res = recvfrom(janus_force_rtcpmux_blackhole_fd, buffer, sizeof(buffer), 0, (struct sockaddr*)&addr, &len);
} while(res > -1);
}
return G_SOURCE_CONTINUE;
}
static gpointer janus_ice_handles_watchdog(gpointer user_data) {
GMainLoop *loop = (GMainLoop *) user_data;
GMainContext *watchdog_context = g_main_loop_get_context(loop);
GSource *timeout_source;
timeout_source = g_timeout_source_new_seconds(1);
g_source_set_callback(timeout_source, janus_ice_handles_check, watchdog_context, NULL);
g_source_attach(timeout_source, watchdog_context);
g_source_unref(timeout_source);
JANUS_LOG(LOG_INFO, "ICE handles watchdog started\n");
g_main_loop_run(loop);
return NULL;
}
void janus_ice_notify_media(janus_ice_handle *handle, gboolean video, gboolean up);
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));
json_object_set_new(event, "type", json_string(video ? "video" : "audio"));
json_object_set_new(event, "receiving", json_string(up ? "true" : "false"));
/* Send the event */
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Sending event to transport...\n", handle->handle_id);
janus_session_notify_event(session->session_id, event);
}
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\n", handle->handle_id);
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(reason != NULL)
json_object_set_new(event, "reason", json_string(reason));
/* Send the event */
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Sending event to transport...\n", handle->handle_id);
janus_session_notify_event(session->session_id, event);
}
/* Trickle helpers */
janus_ice_trickle *janus_ice_trickle_new(janus_ice_handle *handle, const char *transaction, json_t *candidate) {
if(transaction == NULL || candidate == NULL)
return NULL;
janus_ice_trickle *trickle = g_malloc0(sizeof(janus_ice_trickle));
trickle->handle = handle;
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) {
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) {
*error = "Trickle error: missing mandatory element (sdpMid)";
return JANUS_ERROR_MISSING_MANDATORY_ELEMENT;
}
if(!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) {
*error = "Trickle error: missing mandatory element (sdpMLineIndex)";
return JANUS_ERROR_MISSING_MANDATORY_ELEMENT;
}
if(!json_is_integer(mline) || json_integer_value(mline) < 0) {
*error = "Trickle error: invalid element type (sdpMLineIndex should be an integer)";
return JANUS_ERROR_INVALID_ELEMENT_TYPE;
}
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 = json_integer_value(mline);
int video = 0, data = 0;
/* FIXME badly, we should have an array of m-lines in the handle object */
switch(sdpMLineIndex) {
case 0:
if(handle->audio_stream == NULL) {
video = handle->video_stream ? 1 : 0;
data = !video;
}
break;
case 1:
if(handle->audio_stream == NULL) {
data = 1;
} else {
video = handle->video_stream ? 1 : 0;
data = !video;
}
break;
case 2:
data = 1;
break;
default:
/* FIXME We don't support more than 3 m-lines right now */
*error = "Trickle error: invalid element type (sdpMLineIndex not [0,2])";
return JANUS_ERROR_INVALID_ELEMENT_TYPE;
}
#ifndef HAVE_SCTP
data = 0;
#endif
if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)
&& sdpMLineIndex != 0) {
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Got a %s candidate but we're bundling, ignoring...\n", handle->handle_id, json_string_value(mid));
} else {
janus_ice_stream *stream = video ? handle->video_stream : (data ? handle->data_stream : handle->audio_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;
trickle->handle = NULL;
if(trickle->transaction)
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 ipv6, uint16_t rtp_min_port, uint16_t rtp_max_port) {
janus_ice_lite_enabled = ice_lite;
janus_ice_tcp_enabled = ice_tcp;
janus_ipv6_enabled = ipv6;
JANUS_LOG(LOG_INFO, "Initializing ICE stuff (%s mode, ICE-TCP candidates %s, IPv6 support %s)\n",
janus_ice_lite_enabled ? "Lite" : "Full",
janus_ice_tcp_enabled ? "enabled" : "disabled",
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, "ICE-TCP only works in libnice if you enable ICE Lite too: disabling ICE-TCP support\n");
janus_ice_tcp_enabled = FALSE;
}
#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
}
/* We keep track of old plugin sessions to avoid problems */
old_plugin_sessions = g_hash_table_new(NULL, NULL);
janus_mutex_init(&old_plugin_sessions_mutex);
/* Start the handles watchdog */
janus_mutex_init(&old_handles_mutex);
old_handles = g_hash_table_new(NULL, NULL);
handles_watchdog_context = g_main_context_new();
handles_watchdog_loop = g_main_loop_new(handles_watchdog_context, FALSE);
GError *error = NULL;
handles_watchdog = g_thread_try_new("handles watchdog", &janus_ice_handles_watchdog, handles_watchdog_loop, &error);
if(error != NULL) {
JANUS_LOG(LOG_FATAL, "Got error %d (%s) trying to start handles watchdog...\n", error->code, error->message ? error->message : "??");
exit(1);
}
#ifdef HAVE_LIBCURL
/* 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) {
JANUS_LOG(LOG_INFO, "Ending ICE handles watchdog mainloop...\n");
g_main_loop_quit(handles_watchdog_loop);
g_thread_join(handles_watchdog);
handles_watchdog = NULL;
g_main_loop_unref(handles_watchdog_loop);
g_main_context_unref(handles_watchdog_context);
janus_mutex_lock(&old_handles_mutex);
if(old_handles != NULL)
g_hash_table_destroy(old_handles);
old_handles = NULL;
janus_mutex_unlock(&old_handles_mutex);
#ifdef HAVE_LIBCURL
janus_turnrest_deinit();
#endif
}
int janus_ice_set_stun_server(gchar *stun_server, uint16_t stun_port) {
if(stun_server == NULL)
return 0; /* No initialization needed */
if(stun_port == 0)
stun_port = 3478;
JANUS_LOG(LOG_INFO, "STUN server to use: %s:%u\n", stun_server, stun_port);
/* Resolve address to get an IP */
struct addrinfo *res = NULL;
if(getaddrinfo(stun_server, NULL, NULL, &res) != 0) {
JANUS_LOG(LOG_ERR, "Could not resolve %s...\n", stun_server);
if(res)
freeaddrinfo(res);
return -1;
}
janus_stun_server = janus_address_to_ip(res->ai_addr);
freeaddrinfo(res);
if(janus_stun_server == NULL) {
JANUS_LOG(LOG_ERR, "Could not resolve %s...\n", stun_server);
return -1;
}
janus_stun_port = stun_port;
JANUS_LOG(LOG_VERB, " >> %s:%u\n", janus_stun_server, janus_stun_port);
/* 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);
int fd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in address, remote;
address.sin_family = AF_INET;
address.sin_port = 0;
address.sin_addr.s_addr = INADDR_ANY;
remote.sin_family = AF_INET;
remote.sin_port = htons(janus_stun_port);
remote.sin_addr.s_addr = inet_addr(janus_stun_server);
if(bind(fd, (struct sockaddr *)(&address), sizeof(struct sockaddr)) < 0) {
JANUS_LOG(LOG_FATAL, "Bind failed for STUN BINDING test\n");
return -1;
}
int bytes = sendto(fd, buf, len, 0, (struct sockaddr*)&remote, sizeof(remote));
if(bytes < 0) {
JANUS_LOG(LOG_FATAL, "Error sending STUN BINDING test\n");
return -1;
}
JANUS_LOG(LOG_VERB, " >> Sent %d bytes %s:%u, waiting for reply...\n", bytes, janus_stun_server, janus_stun_port);
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;
select(fd+1, &readfds, NULL, NULL, &timeout);
if(!FD_ISSET(fd, &readfds)) {
JANUS_LOG(LOG_FATAL, "No response to our STUN BINDING test\n");
return -1;
}
socklen_t addrlen = sizeof(remote);
bytes = recvfrom(fd, buf, 1500, 0, (struct sockaddr*)&remote, &addrlen);
JANUS_LOG(LOG_VERB, " >> Got %d bytes...\n", bytes);
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) {
char *public_ip = janus_address_to_ip((struct sockaddr *)&address);
JANUS_LOG(LOG_INFO, " >> Our public address is %s\n", public_ip);
janus_set_public_ip(public_ip);
g_free(public_ip);
return 0;
}
ret = stun_message_find_addr(&msg, STUN_ATTRIBUTE_MAPPED_ADDRESS, (struct sockaddr_storage *)&address, &addrlen);
JANUS_LOG(LOG_VERB, " >> MAPPED-ADDRESS: %d\n", ret);
if(ret == STUN_MESSAGE_RETURN_SUCCESS) {
char *public_ip = janus_address_to_ip((struct sockaddr *)&address);
JANUS_LOG(LOG_INFO, " >> Our public address is %s\n", public_ip);
janus_set_public_ip(public_ip);
g_free(public_ip);
return 0;
}
return -1;
}
int janus_ice_set_turn_server(gchar *turn_server, uint16_t turn_port, gchar *turn_type, gchar *turn_user, gchar *turn_pwd) {
if(turn_server == NULL)
return 0; /* No initialization needed */
if(turn_type == NULL)
turn_type = (char *)"udp";
if(turn_port == 0)
turn_port = 3478;
JANUS_LOG(LOG_INFO, "TURN server to use: %s:%u (%s)\n", turn_server, turn_port, turn_type);
if(!strcasecmp(turn_type, "udp")) {
janus_turn_type = NICE_RELAY_TYPE_TURN_UDP;
} else if(!strcasecmp(turn_type, "tcp")) {
janus_turn_type = NICE_RELAY_TYPE_TURN_TCP;
} else if(!strcasecmp(turn_type, "tls")) {
janus_turn_type = NICE_RELAY_TYPE_TURN_TLS;
} else {
JANUS_LOG(LOG_ERR, "Unsupported relay type '%s'...\n", turn_type);
return -1;
}
/* Resolve address to get an IP */
struct addrinfo *res = NULL;
if(getaddrinfo(turn_server, NULL, NULL, &res) != 0) {
JANUS_LOG(LOG_ERR, "Could not resolve %s...\n", turn_server);
if(res)
freeaddrinfo(res);
return -1;
}
if(janus_turn_server != NULL)
g_free(janus_turn_server);
janus_turn_server = janus_address_to_ip(res->ai_addr);
freeaddrinfo(res);
if(janus_turn_server == NULL) {
JANUS_LOG(LOG_ERR, "Could not resolve %s...\n", turn_server);
return -1;
}
janus_turn_port = turn_port;
JANUS_LOG(LOG_VERB, " >> %s:%u\n", janus_turn_server, janus_turn_port);
if(janus_turn_user != NULL)
g_free(janus_turn_user);
janus_turn_user = NULL;
if(turn_user)
janus_turn_user = g_strdup(turn_user);
if(janus_turn_pwd != NULL)
g_free(janus_turn_pwd);
janus_turn_pwd = NULL;
if(turn_pwd)
janus_turn_pwd = g_strdup(turn_pwd);
return 0;
}
int janus_ice_set_turn_rest_api(gchar *api_server, gchar *api_key) {
#ifndef HAVE_LIBCURL
JANUS_LOG(LOG_ERR, "Janus has been nuilt with no libcurl support, TURN REST API unavailable\n");
return -1;
#else
if(api_server != NULL &&
(strstr(api_server, "http://") != api_server && strstr(api_server, "https://") != api_server)) {
JANUS_LOG(LOG_ERR, "Invalid TURN REST API backend: not an HTTP address\n");
return -1;
}
janus_turnrest_set_backend(api_server, api_key);
JANUS_LOG(LOG_INFO, "TURN REST API backend: %s\n", api_server ? api_server : "(disabled)");
#endif
return 0;
}
/* ICE stuff */
static const gchar *janus_ice_state_name[] =
{
"disconnected",
"gathering",
"connecting",
"connected",
"ready",
"failed"
};
const gchar *janus_get_ice_state_name(gint state) {
if(state < 0 || state > 5)
return NULL;
return janus_ice_state_name[state];
}
/* Stats */
void janus_ice_stats_queue_free(gpointer data);
void janus_ice_stats_queue_free(gpointer data) {
janus_ice_stats_item *s = (janus_ice_stats_item *)data;
g_free(s);
}
void janus_ice_stats_reset(janus_ice_stats *stats) {
if(stats == NULL)
return;
stats->audio_packets = 0;
stats->audio_bytes = 0;
if(stats->audio_bytes_lastsec)
g_list_free_full(stats->audio_bytes_lastsec, &janus_ice_stats_queue_free);
stats->audio_bytes_lastsec = NULL;
stats->audio_notified_lastsec = FALSE;
stats->audio_nacks = 0;
stats->video_packets = 0;
stats->video_bytes = 0;
if(stats->video_bytes_lastsec)
g_list_free_full(stats->video_bytes_lastsec, &janus_ice_stats_queue_free);
stats->video_bytes_lastsec = NULL;
stats->video_notified_lastsec = FALSE;
stats->video_nacks = 0;
stats->data_packets = 0;
stats->data_bytes = 0;
}
/* ICE Handles */
janus_ice_handle *janus_ice_handle_create(void *gateway_session) {
if(gateway_session == NULL)
return NULL;
janus_session *session = (janus_session *)gateway_session;
guint64 handle_id = 0;
while(handle_id == 0) {
handle_id = g_random_int();
if(janus_ice_handle_find(gateway_session, handle_id) != NULL) {
/* Handle ID already taken, try another one */
handle_id = 0;
}
}
JANUS_LOG(LOG_INFO, "Creating new handle in session %"SCNu64": %"SCNu64"\n", session->session_id, handle_id);
janus_ice_handle *handle = (janus_ice_handle *)g_malloc0(sizeof(janus_ice_handle));
if(handle == NULL) {
JANUS_LOG(LOG_FATAL, "Memory error!\n");
return NULL;
}
handle->session = gateway_session;
handle->created = janus_get_monotonic_time();
handle->handle_id = handle_id;
handle->app = NULL;
handle->app_handle = NULL;
janus_mutex_init(&handle->mutex);
/* Set up other stuff. */
janus_mutex_lock(&session->mutex);
if(session->ice_handles == NULL)
session->ice_handles = g_hash_table_new(NULL, NULL);
g_hash_table_insert(session->ice_handles, GUINT_TO_POINTER(handle_id), handle);
janus_mutex_unlock(&session->mutex);
return handle;
}
janus_ice_handle *janus_ice_handle_find(void *gateway_session, guint64 handle_id) {
if(gateway_session == NULL)
return NULL;
janus_session *session = (janus_session *)gateway_session;
janus_mutex_lock(&session->mutex);
janus_ice_handle *handle = session->ice_handles ? g_hash_table_lookup(session->ice_handles, GUINT_TO_POINTER(handle_id)) : NULL;
janus_mutex_unlock(&session->mutex);
return handle;
}
gint janus_ice_handle_attach_plugin(void *gateway_session, guint64 handle_id, janus_plugin *plugin) {
if(gateway_session == NULL)
return JANUS_ERROR_SESSION_NOT_FOUND;
if(plugin == NULL)
return JANUS_ERROR_PLUGIN_NOT_FOUND;
janus_session *session = (janus_session *)gateway_session;
janus_ice_handle *handle = janus_ice_handle_find(session, handle_id);
if(handle == NULL)
return JANUS_ERROR_HANDLE_NOT_FOUND;
janus_mutex_lock(&session->mutex);
if(handle->app != NULL) {
/* This handle is already attached to a plugin */
janus_mutex_unlock(&session->mutex);
return JANUS_ERROR_PLUGIN_ATTACH;
}
int error = 0;
janus_plugin_session *session_handle = g_malloc0(sizeof(janus_plugin_session));
if(session_handle == NULL) {
JANUS_LOG(LOG_FATAL, "Memory error!\n");
janus_mutex_unlock(&session->mutex);
return JANUS_ERROR_UNKNOWN; /* FIXME Do we need something like "Internal Server Error"? */
}
session_handle->gateway_handle = handle;
session_handle->plugin_handle = NULL;
session_handle->stopped = 0;
plugin->create_session(session_handle, &error);
if(error) {
/* TODO Make error struct to pass verbose information */
janus_mutex_unlock(&session->mutex);
return error;
}
handle->app = plugin;
handle->app_handle = session_handle;
/* Make sure this plugin session is not in the old sessions list */
janus_mutex_lock(&old_plugin_sessions_mutex);
g_hash_table_remove(old_plugin_sessions, session_handle);
janus_mutex_unlock(&old_plugin_sessions_mutex);
janus_mutex_unlock(&session->mutex);
return 0;
}
gint janus_ice_handle_destroy(void *gateway_session, guint64 handle_id) {
if(gateway_session == NULL)
return JANUS_ERROR_SESSION_NOT_FOUND;
janus_session *session = (janus_session *)gateway_session;
janus_ice_handle *handle = janus_ice_handle_find(session, handle_id);
if(handle == NULL)
return JANUS_ERROR_HANDLE_NOT_FOUND;
janus_mutex_lock(&session->mutex);
janus_plugin *plugin_t = (janus_plugin *)handle->app;
if(plugin_t == NULL) {
/* There was no plugin attached, probably something went wrong there */
janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT);
janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP);
if(handle->iceloop)
g_main_loop_quit(handle->iceloop);
janus_mutex_unlock(&session->mutex);
return 0;
}
JANUS_LOG(LOG_INFO, "Detaching handle from %s\n", plugin_t->get_name());
/* TODO Actually detach handle... */
int error = 0;
janus_mutex_lock(&old_plugin_sessions_mutex);
/* This is to tell the plugin to stop using this session: we'll get rid of it later */
handle->app_handle->stopped = 1;
/* And this is to put the plugin session in the old sessions list, to avoid it being used */
g_hash_table_insert(old_plugin_sessions, handle->app_handle, handle->app_handle);
janus_mutex_unlock(&old_plugin_sessions_mutex);
/* Notify the plugin that the session's over */
plugin_t->destroy_session(handle->app_handle, &error);
/* Get rid of the handle now */
janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT);
janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP);
if(handle->iceloop)
g_main_loop_quit(handle->iceloop);
/* Prepare JSON event to notify user/application */
json_t *event = json_object();
json_object_set_new(event, "janus", json_string("detached"));
json_object_set_new(event, "session_id", json_integer(session->session_id));
json_object_set_new(event, "sender", json_integer(handle_id));
/* Send the event */
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Sending event to transport...\n", handle->handle_id);
janus_session_notify_event(session->session_id, event);
janus_mutex_unlock(&session->mutex);