forked from meetecho/janus-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathice.c
1802 lines (1743 loc) · 72 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 <sys/socket.h>
#include <netdb.h>
#include <stun/usages/bind.h>
#include <nice/debug.h>
#include "janus.h"
#include "debug.h"
#include "ice.h"
#include "dtls.h"
#include "rtp.h"
#include "rtcp.h"
#include "apierror.h"
/* STUN server/port, if any */
static char *janus_stun_server;
static uint16_t janus_stun_port;
char *janus_ice_get_stun_server(void) {
return janus_stun_server;
}
uint16_t janus_ice_get_stun_port(void) {
return janus_stun_port;
}
/* IPv6 support (still mostly WIP) */
static gboolean janus_ipv6_enabled;
gboolean janus_ice_is_ipv6_enabled(void) {
return janus_ipv6_enabled;
}
/* 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);
}
JANUS_LOG(LOG_VERB, "Debugging NICE_DEBUG=%s\n", g_getenv("NICE_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);
}
/* Interface/IP ignore list */
GList *janus_ice_ignore_list = NULL;
janus_mutex ignore_list_mutex;
void janus_ice_ignore_interface(const char *ip) {
if(ip == NULL)
return;
/* Is this an IP or an interface? */
janus_mutex_lock(&ignore_list_mutex);
janus_ice_ignore_list = g_list_append(janus_ice_ignore_list, (gpointer)ip);
janus_mutex_unlock(&ignore_list_mutex);
}
gboolean janus_ice_is_ignored(const char *ip) {
if(ip == NULL || janus_ice_ignore_list == NULL)
return false;
janus_mutex_lock(&ignore_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(&ignore_list_mutex);
return true;
}
temp = temp->next;
}
janus_mutex_unlock(&ignore_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));
}
/* 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;
}
/* libnice initialization */
gint janus_ice_init(gchar *stun_server, uint16_t stun_port, uint16_t rtp_min_port, uint16_t rtp_max_port, gboolean ipv6) {
janus_ipv6_enabled = ipv6;
JANUS_LOG(LOG_INFO, "Initializing ICE stuff (IPv6 candidates %s)\n", janus_ipv6_enabled ? "enabled" : "disabled");
/* Automatically enable libnice debugging based on debug_level */
if(log_level >= LOG_DBG) {
janus_ice_debugging_enable();
} else {
nice_debug_disable(TRUE);
}
if(stun_server == NULL)
return 0; /* No initialization needed */
if(stun_port == 0)
stun_port = 3478;
/*! \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;
#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
JANUS_LOG(LOG_INFO, "STUN server to use: %s:%u\n", stun_server, stun_port);
/* Resolve address to get an IP */
struct hostent *he = gethostbyname(stun_server);
if(he == NULL) {
JANUS_LOG(LOG_ERR, "Could not resolve %s...\n", stun_server);
return -1;
}
struct in_addr **addr_list = (struct in_addr **)he->h_addr_list;
if(addr_list[0] == NULL) {
JANUS_LOG(LOG_ERR, "Could not resolve %s...\n", stun_server);
return -1;
}
janus_stun_server = g_strdup(inet_ntoa(*addr_list[0]));
if(janus_stun_server == NULL) {
JANUS_LOG(LOG_FATAL, "Memory error!\n");
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);
int yes = 1; /* For setsockopt() SO_REUSEADDR */
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
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 *)&address, &addrlen);
JANUS_LOG(LOG_VERB, " >> XOR-MAPPED-ADDRESS: %d\n", ret);
if(ret == STUN_MESSAGE_RETURN_SUCCESS) {
JANUS_LOG(LOG_INFO, " >> Our public address is %s\n", inet_ntoa(address.sin_addr));
return 0;
}
ret = stun_message_find_addr(&msg, STUN_ATTRIBUTE_MAPPED_ADDRESS, (struct sockaddr *)&address, &addrlen);
JANUS_LOG(LOG_VERB, " >> MAPPED-ADDRESS: %d\n", ret);
if(ret == STUN_MESSAGE_RETURN_SUCCESS) {
JANUS_LOG(LOG_INFO, " >> Our public address is %s\n", inet_ntoa(address.sin_addr));
return 0;
}
return -1;
}
/* 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];
}
/* 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 *)calloc(1, sizeof(janus_ice_handle));
if(handle == NULL) {
JANUS_LOG(LOG_FATAL, "Memory error!\n");
return NULL;
}
handle->session = gateway_session;
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 = calloc(1, 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;
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_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP);
janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT);
if(handle->iceloop)
g_main_loop_quit(handle->iceloop);
janus_plugin *plugin_t = (janus_plugin *)handle->app;
if(plugin_t == NULL) {
/* There was no plugin attached, probably something went wrong there */
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;
handle->app_handle->stopped = 1; /* This is to tell the plugin to stop using this session: we'll get rid of it later */
plugin_t->destroy_session(handle->app_handle, &error);
/* 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, "sender", json_integer(handle_id));
/* Convert to a string */
char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
json_decref(event);
/* Send the event before we do anything */
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Adding event to queue of messages...\n", handle_id);
janus_http_event *notification = (janus_http_event *)calloc(1, sizeof(janus_http_event));
if(notification) {
notification->code = 200;
notification->payload = event_text;
notification->allocated = 1;
g_async_queue_push(session->messages, notification);
}
janus_mutex_unlock(&session->mutex);
/* We only actually destroy the handle later */
JANUS_LOG(LOG_INFO, "Handle detached (%d), scheduling destruction\n", error);
return error;
}
void janus_ice_free(janus_ice_handle *handle) {
if(handle == NULL)
return;
janus_mutex_lock(&handle->mutex);
handle->session = NULL;
handle->app = NULL;
if(handle->app_handle != NULL) {
handle->app_handle->stopped = 1;
handle->app_handle->gateway_handle = NULL;
handle->app_handle->plugin_handle = NULL;
g_free(handle->app_handle);
handle->app_handle = NULL;
}
janus_mutex_unlock(&handle->mutex);
janus_ice_webrtc_free(handle);
JANUS_LOG(LOG_INFO, "[%"SCNu64"] Handle and related resources freed\n", handle->handle_id);
g_free(handle);
handle = NULL;
}
void janus_ice_webrtc_hangup(janus_ice_handle *handle) {
if(handle == NULL)
return;
janus_mutex_lock(&handle->mutex);
handle->icethread = NULL;
if(handle->streams != NULL) {
if(handle->audio_stream) {
janus_ice_stream *stream = handle->audio_stream;
if(stream->rtp_component)
janus_dtls_srtp_send_alert(stream->rtp_component->dtls);
if(stream->rtcp_component)
janus_dtls_srtp_send_alert(stream->rtcp_component->dtls);
}
if(handle->video_stream) {
janus_ice_stream *stream = handle->video_stream;
if(stream->rtp_component)
janus_dtls_srtp_send_alert(stream->rtp_component->dtls);
if(stream->rtcp_component)
janus_dtls_srtp_send_alert(stream->rtcp_component->dtls);
}
if(handle->data_stream) {
janus_ice_stream *stream = handle->data_stream;
if(stream->rtp_component)
janus_dtls_srtp_send_alert(stream->rtp_component->dtls);
if(stream->rtcp_component)
janus_dtls_srtp_send_alert(stream->rtcp_component->dtls);
}
}
janus_mutex_unlock(&handle->mutex);
}
void janus_ice_webrtc_free(janus_ice_handle *handle) {
if(handle == NULL)
return;
janus_mutex_lock(&handle->mutex);
if(handle->iceloop != NULL) {
g_main_loop_unref (handle->iceloop);
handle->iceloop = NULL;
}
if(handle->icectx != NULL) {
g_main_context_unref (handle->icectx);
handle->icectx = NULL;
}
handle->icethread = NULL;
if(handle->streams != NULL) {
janus_ice_stream_free(handle->streams, handle->audio_stream);
handle->audio_stream = NULL;
janus_ice_stream_free(handle->streams, handle->video_stream);
handle->video_stream = NULL;
janus_ice_stream_free(handle->streams, handle->data_stream);
handle->data_stream = NULL;
g_hash_table_destroy(handle->streams);
handle->streams = NULL;
}
if(handle->agent != NULL) {
if(G_IS_OBJECT(handle->agent))
g_object_unref(handle->agent);
handle->agent = NULL;
}
if(handle->remote_hashing != NULL) {
g_free(handle->remote_hashing);
handle->remote_hashing = NULL;
}
if(handle->remote_fingerprint != NULL) {
g_free(handle->remote_fingerprint);
handle->remote_fingerprint = NULL;
}
if(handle->local_sdp != NULL) {
g_free(handle->local_sdp);
handle->local_sdp = NULL;
}
if(handle->remote_sdp != NULL) {
g_free(handle->remote_sdp);
handle->remote_sdp = NULL;
}
if(handle->queued_packets != NULL) {
janus_ice_queued_packet *pkt = NULL;
while(g_async_queue_length(handle->queued_packets) > 0) {
pkt = g_async_queue_try_pop(handle->queued_packets);
if(pkt != NULL) {
g_free(pkt->data);
pkt->data = NULL;
g_free(pkt);
pkt = NULL;
}
}
g_async_queue_unref(handle->queued_packets);
handle->queued_packets = NULL;
}
janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_READY);
janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_CLEANING);
janus_mutex_unlock(&handle->mutex);
JANUS_LOG(LOG_INFO, "[%"SCNu64"] WebRTC resources freed\n", handle->handle_id);
}
void janus_ice_stream_free(GHashTable *streams, janus_ice_stream *stream) {
if(stream == NULL)
return;
if(streams != NULL)
g_hash_table_remove(streams, stream);
if(stream->components != NULL) {
janus_ice_component_free(stream->components, stream->rtp_component);
stream->rtp_component = NULL;
janus_ice_component_free(stream->components, stream->rtcp_component);
stream->rtcp_component = NULL;
g_hash_table_destroy(stream->components);
}
stream->handle = NULL;
if(stream->ruser != NULL) {
g_free(stream->ruser);
stream->ruser = NULL;
}
if(stream->rpass != NULL) {
g_free(stream->rpass);
stream->rpass = NULL;
}
g_free(stream);
stream = NULL;
}
void janus_ice_component_free(GHashTable *components, janus_ice_component *component) {
if(component == NULL)
return;
janus_ice_stream *stream = component->stream;
if(stream == NULL)
return;
janus_ice_handle *handle = stream->handle;
if(handle == NULL)
return;
//~ janus_mutex_lock(&handle->mutex);
if(components != NULL)
g_hash_table_remove(components, component);
component->stream = NULL;
if(component->source != NULL) {
g_source_destroy(component->source);
if(G_IS_OBJECT(component->source))
g_object_unref(component->source);
component->source = NULL;
}
if(component->dtls != NULL) {
janus_dtls_srtp_destroy(component->dtls);
component->dtls = NULL;
}
if(component->retransmit_buffer != NULL) {
janus_rtp_packet *p = NULL;
GList *first = g_list_first(component->retransmit_buffer);
while(first != NULL) {
p = (janus_rtp_packet *)first->data;
first->data = NULL;
component->retransmit_buffer = g_list_delete_link(component->retransmit_buffer, first);
g_free(p->data);
p->data = NULL;
g_free(p);
first = g_list_first(component->retransmit_buffer);
}
}
if(component->candidates != NULL) {
GSList *i = NULL, *candidates = component->candidates;
for (i = candidates; i; i = i->next) {
NiceCandidate *c = (NiceCandidate *) i->data;
if(c != NULL) {
nice_candidate_free(c);
c = NULL;
}
}
g_slist_free(candidates);
candidates = NULL;
}
component->candidates = NULL;
if(component->local_candidates != NULL) {
GSList *i = NULL, *candidates = component->local_candidates;
for (i = candidates; i; i = i->next) {
gchar *c = (gchar *) i->data;
if(c != NULL) {
g_free(c);
c = NULL;
}
}
g_slist_free(candidates);
candidates = NULL;
}
component->local_candidates = NULL;
if(component->remote_candidates != NULL) {
GSList *i = NULL, *candidates = component->remote_candidates;
for (i = candidates; i; i = i->next) {
gchar *c = (gchar *) i->data;
if(c != NULL) {
g_free(c);
c = NULL;
}
}
g_slist_free(candidates);
candidates = NULL;
}
component->remote_candidates = NULL;
g_free(component);
//~ janus_mutex_unlock(&handle->mutex);
}
/* Callbacks */
void janus_ice_cb_candidate_gathering_done(NiceAgent *agent, guint stream_id, gpointer user_data) {
janus_ice_handle *handle = (janus_ice_handle *)user_data;
if(!handle)
return;
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Gathering done for stream %d\n", handle->handle_id, stream_id);
handle->cdone++;
janus_ice_stream *stream = g_hash_table_lookup(handle->streams, GUINT_TO_POINTER(stream_id));
if(!stream) {
JANUS_LOG(LOG_ERR, "[%"SCNu64"] No stream %d??\n", handle->handle_id, stream_id);
return;
}
stream->cdone = 1;
}
void janus_ice_cb_component_state_changed(NiceAgent *agent, guint stream_id, guint component_id, guint state, gpointer ice) {
janus_ice_handle *handle = (janus_ice_handle *)ice;
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Component state changed for component %d in stream %d: %d (%s)\n",
handle ? handle->handle_id : 0, component_id, stream_id, state, janus_get_ice_state_name(state));
if(!handle)
return;
janus_ice_stream *stream = g_hash_table_lookup(handle->streams, GUINT_TO_POINTER(stream_id));
if(!stream) {
JANUS_LOG(LOG_ERR, "[%"SCNu64"] No stream %d??\n", handle->handle_id, stream_id);
return;
}
janus_ice_component *component = g_hash_table_lookup(stream->components, GUINT_TO_POINTER(component_id));
if(!component) {
JANUS_LOG(LOG_ERR, "[%"SCNu64"] No component %d in stream %d??\n", handle->handle_id, component_id, stream_id);
return;
}
component->state = state;
/* FIXME Even in case the state is 'connected', we wait for the 'new-selected-pair' callback to do anything */
if(state == NICE_COMPONENT_STATE_FAILED) {
/* Failed doesn't mean necessarily we need to give up: we may be trickling */
if(handle &&
(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_TRICKLE) || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALL_TRICKLES))
&& !janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT)) {
/* FIXME Should we really give up for what may be a failure in only one of the media? */
JANUS_LOG(LOG_ERR, "ICE failed for handle %"SCNu64"...\n", handle->handle_id);
janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT);
janus_plugin *plugin = (janus_plugin *)handle->app;
if(plugin != NULL) {
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Telling the plugin about it (%s)\n", handle->handle_id, plugin->get_name());
if(plugin && plugin->hangup_media)
plugin->hangup_media(handle->app_handle);
}
/* Also prepare JSON event to notify user/application */
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));
/* Convert to a string */
char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
json_decref(event);
/* Send the event */
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Adding event to queue of messages...\n", handle->handle_id);
janus_http_event *notification = (janus_http_event *)calloc(1, sizeof(janus_http_event));
if(notification == NULL) {
JANUS_LOG(LOG_FATAL, "Memory error!\n");
return;
}
notification->code = 200;
notification->payload = event_text;
notification->allocated = 1;
g_async_queue_push(session->messages, notification);
}
}
}
void janus_ice_cb_new_selected_pair(NiceAgent *agent, guint stream_id, guint component_id, gchar *lfoundation, gchar *rfoundation, gpointer ice) {
janus_ice_handle *handle = (janus_ice_handle *)ice;
JANUS_LOG(LOG_VERB, "[%"SCNu64"] New selected pair for component %d in stream %d: %s <-> %s\n", handle ? handle->handle_id : 0, component_id, stream_id, lfoundation, rfoundation);
if(!handle)
return;
janus_ice_stream *stream = g_hash_table_lookup(handle->streams, GUINT_TO_POINTER(stream_id));
if(!stream) {
JANUS_LOG(LOG_ERR, "[%"SCNu64"] No stream %d??\n", handle->handle_id, stream_id);
return;
}
janus_ice_component *component = g_hash_table_lookup(stream->components, GUINT_TO_POINTER(component_id));
if(!component) {
JANUS_LOG(LOG_ERR, "[%"SCNu64"] No component %d in stream %d??\n", handle->handle_id, component_id, stream_id);
return;
}
/* Now we can start the DTLS handshake (FIXME This was on the 'connected' state notification, before) */
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Component is ready enough, starting DTLS handshake...\n", handle->handle_id);
/* Have we been here before? (might happen, when trickling) */
if(component->dtls != NULL)
return;
/* Create DTLS-SRTP context, at last */
component->dtls = janus_dtls_srtp_create(component, stream->dtls_role);
if(!component->dtls) {
JANUS_LOG(LOG_ERR, "[%"SCNu64"] No component DTLS-SRTP session??\n", handle->handle_id);
return;
}
/* Create retransmission timer */
component->source = g_timeout_source_new(100);
g_source_set_callback(component->source, janus_dtls_retry, component->dtls, NULL);
guint id = g_source_attach(component->source, handle->icectx);
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Creating retransmission timer with ID %u\n", handle->handle_id, id);
}
void janus_ice_cb_nice_recv(NiceAgent *agent, guint stream_id, guint component_id, guint len, gchar *buf, gpointer ice) {
janus_ice_component *component = (janus_ice_component *)ice;
if(!component) {
JANUS_LOG(LOG_ERR, "No component %d in stream %d??\n", component_id, stream_id);
return;
}
if(!component->dtls) { /* Still waiting for the DTLS stack */
JANUS_LOG(LOG_ERR, "Still waiting for the DTLS stack for component %d in stream %d...\n", component_id, stream_id);
return;
}
janus_ice_stream *stream = component->stream;
if(!stream) {
JANUS_LOG(LOG_ERR, "No stream %d??\n", stream_id);
return;
}
janus_ice_handle *handle = stream->handle;
if(!handle) {
JANUS_LOG(LOG_ERR, "No handle for stream %d??\n", stream_id);
return;
}
/* What is this? */
if (janus_is_dtls(buf) || (!janus_is_rtp(buf) && !janus_is_rtcp(buf))) {
/* This is DTLS: either handshake stuff, or data coming from SCTP DataChannels */
JANUS_LOG(LOG_HUGE, "Looks like DTLS!\n");
janus_dtls_srtp_incoming_msg(component->dtls, buf, len);
return;
}
/* Not DTLS... RTP or RTCP? (http://tools.ietf.org/html/rfc5761#section-4) */
if(len < 12)
return; /* Definitely nothing useful */
if(component_id == 1 && (!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_RTCPMUX) || janus_is_rtp(buf))) {
/* FIXME If rtcp-mux is not used, a first component is always RTP; otherwise, we need to check */
//~ JANUS_LOG(LOG_HUGE, "[%"SCNu64"] Got an RTP packet (%s stream)!\n", handle->handle_id,
//~ janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE) ? "bundled" : (stream->stream_id == handle->audio_id ? "audio" : "video"));
if(!component->dtls || !component->dtls->srtp_valid) {
JANUS_LOG(LOG_WARN, "[%"SCNu64"] Missing valid SRTP session (packet arrived too early?), skipping...\n", handle->handle_id);
} else {
int buflen = len;
err_status_t res = srtp_unprotect(component->dtls->srtp_in, buf, &buflen);
if(res != err_status_ok) {
JANUS_LOG(LOG_ERR, "[%"SCNu64"] SRTP unprotect error: %s (len=%d-->%d)\n", handle->handle_id, janus_get_srtp_error(res), len, buflen);
} else {
/* Is this audio or video? */
int video = 0;
if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)) {
/* Easy enough */
video = (stream->stream_id == handle->video_id ? 1 : 0);
} else {
/* Bundled streams, check SSRC */
rtp_header *header = (rtp_header *)buf;
video = (stream->video_ssrc_peer == ntohl(header->ssrc) ? 1 : 0);
//~ JANUS_LOG(LOG_VERB, "[RTP] Bundling: this is %s (video=%"SCNu64", audio=%"SCNu64", got %ld)\n",
//~ video ? "video" : "audio", stream->video_ssrc_peer, stream->audio_ssrc_peer, ntohl(header->ssrc));
}
if(video) {
if(stream->video_ssrc_peer == 0) {
rtp_header *header = (rtp_header *)buf;
stream->video_ssrc_peer = ntohl(header->ssrc);
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Peer video SSRC: %u\n", handle->handle_id, stream->video_ssrc_peer);
}
} else {
if(stream->audio_ssrc_peer == 0) {
rtp_header *header = (rtp_header *)buf;
stream->audio_ssrc_peer = ntohl(header->ssrc);
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Peer audio SSRC: %u\n", handle->handle_id, stream->audio_ssrc_peer);
}
}
/* TODO Should we store the packet in a circular buffer, in case we get a NACK we can handle ourselves without relaying? */
janus_plugin *plugin = (janus_plugin *)handle->app;
if(plugin && plugin->incoming_rtp)
plugin->incoming_rtp(handle->app_handle, video, buf, buflen);
}
}
return;
}
if(component_id == 2 || (component_id == 1 && janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_RTCPMUX) && janus_is_rtcp(buf))) {
/* FIXME A second component is always RTCP; in case of rtcp-mux, we need to check */
JANUS_LOG(LOG_HUGE, "[%"SCNu64"] Got an RTCP packet (%s stream)!\n", handle->handle_id,
janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE) ? "bundled" : (stream->stream_id == handle->audio_id ? "audio" : "video"));
if(!component->dtls || !component->dtls->srtp_valid) {
JANUS_LOG(LOG_WARN, "[%"SCNu64"] Missing valid SRTP session (packet arrived too early?), skipping...\n", handle->handle_id);
} else {
int buflen = len;
err_status_t res = srtp_unprotect_rtcp(component->dtls->srtp_in, buf, &buflen);
if(res != err_status_ok) {
JANUS_LOG(LOG_ERR, "[%"SCNu64"] SRTCP unprotect error: %s (len=%d-->%d)\n", handle->handle_id, janus_get_srtp_error(res), len, buflen);
} else {
/* Is this audio or video? */
int video = 0;
if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)) {
/* Easy enough */
video = (stream->stream_id == handle->video_id ? 1 : 0);
} else {
/* TODO Bundled streams, check SSRC */
guint32 rtcp_ssrc = janus_rtcp_get_sender_ssrc(buf, len);
video = (stream->video_ssrc_peer == rtcp_ssrc ? 1 : 0);
//~ JANUS_LOG(LOG_VERB, "[RTCP] Bundling: this is %s (video=%"SCNu64", audio=%"SCNu64", got %ld)\n",
//~ video ? "video" : "audio", stream->video_ssrc_peer, stream->audio_ssrc_peer, rtcp_ssrc);
}
GSList *nacks = janus_rtcp_get_nacks(buf, buflen);
if(nacks != NULL) {
/* Handle NACK */
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Just got some NACKS we should handle...\n", handle->handle_id);
GSList *list = nacks;
gint64 now = janus_get_monotonic_time();
janus_mutex_lock(&component->mutex);
while(list) {
unsigned int seqnr = GPOINTER_TO_UINT(list->data);
JANUS_LOG(LOG_HUGE, " >> %u\n", seqnr);
GList *rp = component->retransmit_buffer;
while(rp) {
janus_rtp_packet *p = (janus_rtp_packet *)rp->data;
if(p) {
rtp_header *rh = (rtp_header *)p->data;
if(ntohs(rh->seq_number) == seqnr) {
/* Should we retransmit this packet? */
if((p->last_retransmit > 0) && (now-p->last_retransmit < MAX_NACK_IGNORE)) {
JANUS_LOG(LOG_HUGE, " >> >> Packet %u was retransmitted just %"SCNi64"ms ago, skipping\n", seqnr, now-p->last_retransmit);
break;
}
JANUS_LOG(LOG_HUGE, " >> >> Scheduling %u for retransmission!\n", seqnr);
p->last_retransmit = now;
/* Enqueue it */
janus_ice_queued_packet *pkt = (janus_ice_queued_packet *)calloc(1, sizeof(janus_ice_queued_packet));
pkt->data = calloc(p->length, sizeof(char));
memcpy(pkt->data, p->data, p->length);
pkt->length = p->length;
pkt->type = video ? JANUS_ICE_PACKET_VIDEO : JANUS_ICE_PACKET_AUDIO;
pkt->control = FALSE;
pkt->encrypted = TRUE; /* This was already encrypted before */
if(handle->queued_packets != NULL)
g_async_queue_push(handle->queued_packets, pkt);
break;
}
}
rp = rp->next;
}
list = list->next;
}
janus_mutex_unlock(&component->mutex);
JANUS_LOG(LOG_HUGE, "\n");
g_slist_free(nacks);
nacks = NULL;
/* FIXME Remove the NACK compound packet, we've handled it */
buflen = janus_rtcp_remove_nacks(buf, buflen);
}
janus_plugin *plugin = (janus_plugin *)handle->app;
if(plugin && plugin->incoming_rtcp)
plugin->incoming_rtcp(handle->app_handle, video, buf, buflen);
}
}
return;
}
if(component_id == 3 || (janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_RTCPMUX)
&& janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_DATA_CHANNELS))) {
JANUS_LOG(LOG_INFO, "Not RTP and not RTCP... may these be data channels?\n");
janus_dtls_srtp_incoming_msg(component->dtls, buf, len);
return;
}
}
void janus_ice_incoming_data(janus_ice_handle *handle, char *buffer, int length) {
if(handle == NULL || buffer == NULL || length <= 0)
return;
janus_plugin *plugin = (janus_plugin *)handle->app;
if(plugin && plugin->incoming_data)
plugin->incoming_data(handle->app_handle, buffer, length);
}
/* Thread to create agent */
void *janus_ice_thread(void *data) {
janus_ice_handle *handle = data;
JANUS_LOG(LOG_VERB, "[%"SCNu64"] ICE thread started, looping...\n", handle->handle_id);
GMainLoop *loop = handle->iceloop;
if(loop == NULL) {
JANUS_LOG(LOG_ERR, "[%"SCNu64"] Invalid loop...\n", handle->handle_id);
g_thread_unref(g_thread_self());
return NULL;
}
g_usleep (100000);
g_main_loop_run (loop);
janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_CLEANING);
if(handle->cdone == 0)
handle->cdone = -1;
JANUS_LOG(LOG_VERB, "[%"SCNu64"] ICE thread ended!\n", handle->handle_id);
/* This handle has been destroyed, wait a bit and then free all the resources */
g_usleep (1*G_USEC_PER_SEC);
if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)) {
janus_ice_free(handle);
} else {
janus_ice_webrtc_free(handle);
}
g_thread_unref(g_thread_self());
return NULL;
}
/* Helper: candidates */
void janus_ice_candidates_to_sdp(janus_ice_handle *handle, char *sdp, guint stream_id, guint component_id)
{
if(!handle || !handle->agent || !sdp)
return;
janus_ice_stream *stream = g_hash_table_lookup(handle->streams, GUINT_TO_POINTER(stream_id));
if(!stream) {
JANUS_LOG(LOG_ERR, "[%"SCNu64"] No stream %d??\n", handle->handle_id, stream_id);
return;
}
janus_ice_component *component = g_hash_table_lookup(stream->components, GUINT_TO_POINTER(component_id));
if(!component) {
JANUS_LOG(LOG_ERR, "[%"SCNu64"] No component %d in stream %d??\n", handle->handle_id, component_id, stream_id);
return;
}
NiceAgent* agent = handle->agent;
/* adding a stream should cause host candidates to be generated */
GSList *candidates, *i;
candidates = nice_agent_get_local_candidates (agent, stream_id, component_id);
JANUS_LOG(LOG_VERB, "[%"SCNu64"] We have %d candidates for Stream #%d, Component #%d\n", handle->handle_id, g_slist_length(candidates), stream_id, component_id);
gboolean log_candidates = (component->local_candidates == NULL);
/* Any provided public IP to consider? */
char *host_ip = NULL;
if(janus_get_public_ip() != janus_get_local_ip()) {
host_ip = janus_get_public_ip();
JANUS_LOG(LOG_VERB, "Public IP specified (%s), using that as host address in the candidates\n", host_ip);
}
for (i = candidates; i; i = i->next) {
NiceCandidate *c = (NiceCandidate *) i->data;
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Stream #%d, Component #%d\n", handle->handle_id, c->stream_id, c->component_id);
gchar address[NICE_ADDRESS_STRING_LEN], base_address[NICE_ADDRESS_STRING_LEN];
gint port = 0, base_port = 0;
nice_address_to_string(&(c->addr), (gchar *)&address);
port = nice_address_get_port(&(c->addr));
nice_address_to_string(&(c->base_addr), (gchar *)&base_address);
base_port = nice_address_get_port(&(c->base_addr));
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Address: %s:%d\n", handle->handle_id, address, port);
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Priority: %d\n", handle->handle_id, c->priority);
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Foundation: %s\n", handle->handle_id, c->foundation);
/* SDP time */
gchar buffer[100];
if(c->type == NICE_CANDIDATE_TYPE_HOST) {
/* 'host' candidate */
g_snprintf(buffer, 100,
"a=candidate:%s %d %s %d %s %d typ host\r\n",
c->foundation,
c->component_id,
"udp",
c->priority,
host_ip ? host_ip : address,
port);
} else if(c->type == NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE) {
/* 'srflx' candidate */
nice_address_to_string(&(c->base_addr), (gchar *)&base_address);
gint base_port = nice_address_get_port(&(c->base_addr));
g_snprintf(buffer, 100,
"a=candidate:%s %d %s %d %s %d typ srflx raddr %s rport %d\r\n",
c->foundation,
c->component_id,
"udp",
c->priority,
address,
port,
base_address,
base_port);
} else if(c->type == NICE_CANDIDATE_TYPE_PEER_REFLEXIVE) {
/* 'prflx' candidate */
g_snprintf(buffer, 100,
"a=candidate:%s %d %s %d %s %d typ prflx raddr %s rport %d\r\n",
c->foundation,
c->component_id,
"udp",
c->priority,
address,
port,
base_address,
base_port);
} else if(c->type == NICE_CANDIDATE_TYPE_RELAYED) {
/* 'relay' candidate */
g_snprintf(buffer, 100,