forked from meetecho/janus-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
janus.c
4268 lines (4100 loc) · 181 KB
/
janus.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 janus.c
* \author Lorenzo Miniero <[email protected]>
* \copyright GNU General Public License v3
* \brief Janus core
* \details Implementation of the gateway core. This code takes care of
* the gateway initialization (command line/configuration) and setup,
* and makes use of the available transport plugins (by default HTTP,
* WebSockets, RabbitMQ, if compiled) and Janus protocol (a JSON-based
* protocol) to interact with the applications, whether they're web based
* or not. The core also takes care of bridging peers and plugins
* accordingly, in terms of both messaging and real-time media transfer
* via WebRTC.
*
* \ingroup core
* \ref core
*/
#include <dlfcn.h>
#include <dirent.h>
#include <net/if.h>
#include <netdb.h>
#include <signal.h>
#include <getopt.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <poll.h>
#include "janus.h"
#include "version.h"
#include "cmdline.h"
#include "config.h"
#include "apierror.h"
#include "log.h"
#include "debug.h"
#include "ip-utils.h"
#include "rtcp.h"
#include "auth.h"
#include "record.h"
#include "events.h"
#define JANUS_NAME "Janus WebRTC Gateway"
#define JANUS_AUTHOR "Meetecho s.r.l."
#define JANUS_VERSION 23
#define JANUS_VERSION_STRING "0.2.3"
#define JANUS_SERVER_NAME "MyJanusInstance"
#ifdef __MACH__
#define SHLIB_EXT "0.dylib"
#else
#define SHLIB_EXT ".so"
#endif
static janus_config *config = NULL;
static char *config_file = NULL;
static char *configs_folder = NULL;
static GHashTable *transports = NULL;
static GHashTable *transports_so = NULL;
static GHashTable *eventhandlers = NULL;
static GHashTable *eventhandlers_so = NULL;
static GHashTable *plugins = NULL;
static GHashTable *plugins_so = NULL;
/* Daemonization */
static gboolean daemonize = FALSE;
static int pipefd[2];
/* API secrets */
static char *api_secret = NULL, *admin_api_secret = NULL;
/* JSON parameters */
static int janus_process_error_string(janus_request *request, uint64_t session_id, const char *transaction, gint error, gchar *error_string);
static struct janus_json_parameter incoming_request_parameters[] = {
{"transaction", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
{"janus", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
{"id", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE}
};
static struct janus_json_parameter attach_parameters[] = {
{"plugin", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
{"opaque_id", JSON_STRING, 0}
};
static struct janus_json_parameter body_parameters[] = {
{"body", JSON_OBJECT, JANUS_JSON_PARAM_REQUIRED}
};
static struct janus_json_parameter jsep_parameters[] = {
{"type", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
{"trickle", JANUS_JSON_BOOL, 0},
{"sdp", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
};
static struct janus_json_parameter allow_token_parameters[] = {
{"token", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
{"plugins", JSON_ARRAY, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_NONEMPTY}
};
static struct janus_json_parameter add_token_parameters[] = {
{"token", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
{"plugins", JSON_ARRAY, 0}
};
static struct janus_json_parameter token_parameters[] = {
{"token", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
};
static struct janus_json_parameter admin_parameters[] = {
{"transaction", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
{"janus", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
};
static struct janus_json_parameter debug_parameters[] = {
{"debug", JANUS_JSON_BOOL, JANUS_JSON_PARAM_REQUIRED}
};
static struct janus_json_parameter timeout_parameters[] = {
{"timeout", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE}
};
static struct janus_json_parameter level_parameters[] = {
{"level", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE}
};
static struct janus_json_parameter timestamps_parameters[] = {
{"timestamps", JANUS_JSON_BOOL, JANUS_JSON_PARAM_REQUIRED}
};
static struct janus_json_parameter colors_parameters[] = {
{"colors", JANUS_JSON_BOOL, JANUS_JSON_PARAM_REQUIRED}
};
static struct janus_json_parameter mnq_parameters[] = {
{"max_nack_queue", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE}
};
static struct janus_json_parameter nmt_parameters[] = {
{"no_media_timer", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE}
};
/* Admin/Monitor helpers */
json_t *janus_admin_stream_summary(janus_ice_stream *stream);
json_t *janus_admin_component_summary(janus_ice_component *component);
/* IP addresses */
static gchar *local_ip = NULL;
gchar *janus_get_local_ip(void) {
return local_ip;
}
static gchar *public_ip = NULL;
gchar *janus_get_public_ip(void) {
/* Fallback to the local IP, if we have no public one */
return public_ip ? public_ip : local_ip;
}
void janus_set_public_ip(const char *ip) {
/* once set do not override */
if(ip == NULL || public_ip != NULL)
return;
public_ip = g_strdup(ip);
}
static volatile gint stop = 0;
static gint stop_signal = 0;
gint janus_is_stopping(void) {
return g_atomic_int_get(&stop);
}
/* Public instance name */
static gchar *server_name = NULL;
/* The default timeout for sessions is 60 seconds: this means that, if
* we don't get any activity (i.e., no request) on this session for more
* than 60 seconds, then it's considered expired and we destroy it. That's
* why we have a keep-alive method in the API. This can be overridden in
* either janus.cfg or from the command line. Setting this to 0 will
* disable the timeout mechanism, which is NOT suggested as it may risk
* having orphaned sessions (sessions not controlled by any transport
* and never freed). Besides, notice that if you make this shorter than
* 30s, you'll have to update the timers in janus.js when the long
* polling mechanism is used and shorten them as well, or you'll risk
* incurring in unexpected timeouts (when HTTP is used in janus.js, the
* long poll is used as a keepalive mechanism). */
#define DEFAULT_SESSION_TIMEOUT 60
static uint session_timeout = DEFAULT_SESSION_TIMEOUT;
/* Information */
static json_t *janus_info(const char *transaction) {
/* Prepare a summary on the gateway */
json_t *info = json_object();
json_object_set_new(info, "janus", json_string("server_info"));
if(transaction != NULL)
json_object_set_new(info, "transaction", json_string(transaction));
json_object_set_new(info, "name", json_string(JANUS_NAME));
json_object_set_new(info, "version", json_integer(JANUS_VERSION));
json_object_set_new(info, "version_string", json_string(JANUS_VERSION_STRING));
json_object_set_new(info, "author", json_string(JANUS_AUTHOR));
json_object_set_new(info, "commit-hash", json_string(janus_build_git_sha));
json_object_set_new(info, "compile-time", json_string(janus_build_git_time));
json_object_set_new(info, "log-to-stdout", janus_log_is_stdout_enabled() ? json_true() : json_false());
json_object_set_new(info, "log-to-file", janus_log_is_logfile_enabled() ? json_true() : json_false());
if(janus_log_is_logfile_enabled())
json_object_set_new(info, "log-path", json_string(janus_log_get_logfile_path()));
#ifdef HAVE_SCTP
json_object_set_new(info, "data_channels", json_true());
#else
json_object_set_new(info, "data_channels", json_false());
#endif
json_object_set_new(info, "session-timeout", json_integer(session_timeout));
json_object_set_new(info, "server-name", json_string(server_name ? server_name : JANUS_SERVER_NAME));
json_object_set_new(info, "local-ip", json_string(local_ip));
if(public_ip != NULL)
json_object_set_new(info, "public-ip", json_string(public_ip));
json_object_set_new(info, "ipv6", janus_ice_is_ipv6_enabled() ? json_true() : json_false());
json_object_set_new(info, "ice-lite", janus_ice_is_ice_lite_enabled() ? json_true() : json_false());
json_object_set_new(info, "ice-tcp", janus_ice_is_ice_tcp_enabled() ? json_true() : json_false());
if(janus_ice_get_stun_server() != NULL) {
char server[255];
g_snprintf(server, 255, "%s:%"SCNu16, janus_ice_get_stun_server(), janus_ice_get_stun_port());
json_object_set_new(info, "stun-server", json_string(server));
}
if(janus_ice_get_turn_server() != NULL) {
char server[255];
g_snprintf(server, 255, "%s:%"SCNu16, janus_ice_get_turn_server(), janus_ice_get_turn_port());
json_object_set_new(info, "turn-server", json_string(server));
}
json_object_set_new(info, "api_secret", api_secret ? json_true() : json_false());
json_object_set_new(info, "auth_token", janus_auth_is_enabled() ? json_true() : json_false());
json_object_set_new(info, "event_handlers", janus_events_is_enabled() ? json_true() : json_false());
/* Available transports */
json_t *t_data = json_object();
if(transports && g_hash_table_size(transports) > 0) {
GHashTableIter iter;
gpointer value;
g_hash_table_iter_init(&iter, transports);
while (g_hash_table_iter_next(&iter, NULL, &value)) {
janus_transport *t = value;
if(t == NULL) {
continue;
}
json_t *transport = json_object();
json_object_set_new(transport, "name", json_string(t->get_name()));
json_object_set_new(transport, "author", json_string(t->get_author()));
json_object_set_new(transport, "description", json_string(t->get_description()));
json_object_set_new(transport, "version_string", json_string(t->get_version_string()));
json_object_set_new(transport, "version", json_integer(t->get_version()));
json_object_set_new(t_data, t->get_package(), transport);
}
}
json_object_set_new(info, "transports", t_data);
/* Available event handlers */
json_t *e_data = json_object();
if(eventhandlers && g_hash_table_size(eventhandlers) > 0) {
GHashTableIter iter;
gpointer value;
g_hash_table_iter_init(&iter, eventhandlers);
while (g_hash_table_iter_next(&iter, NULL, &value)) {
janus_eventhandler *e = value;
if(e == NULL) {
continue;
}
json_t *eventhandler = json_object();
json_object_set_new(eventhandler, "name", json_string(e->get_name()));
json_object_set_new(eventhandler, "author", json_string(e->get_author()));
json_object_set_new(eventhandler, "description", json_string(e->get_description()));
json_object_set_new(eventhandler, "version_string", json_string(e->get_version_string()));
json_object_set_new(eventhandler, "version", json_integer(e->get_version()));
json_object_set_new(e_data, e->get_package(), eventhandler);
}
}
json_object_set_new(info, "events", e_data);
/* Available plugins */
json_t *p_data = json_object();
if(plugins && g_hash_table_size(plugins) > 0) {
GHashTableIter iter;
gpointer value;
g_hash_table_iter_init(&iter, plugins);
while (g_hash_table_iter_next(&iter, NULL, &value)) {
janus_plugin *p = value;
if(p == NULL) {
continue;
}
json_t *plugin = json_object();
json_object_set_new(plugin, "name", json_string(p->get_name()));
json_object_set_new(plugin, "author", json_string(p->get_author()));
json_object_set_new(plugin, "description", json_string(p->get_description()));
json_object_set_new(plugin, "version_string", json_string(p->get_version_string()));
json_object_set_new(plugin, "version", json_integer(p->get_version()));
json_object_set_new(p_data, p->get_package(), plugin);
}
}
json_object_set_new(info, "plugins", p_data);
return info;
}
/* Logging */
int janus_log_level = LOG_INFO;
gboolean janus_log_timestamps = FALSE;
gboolean janus_log_colors = FALSE;
int lock_debug = 0;
/*! \brief Signal handler (just used to intercept CTRL+C and SIGTERM) */
static void janus_handle_signal(int signum) {
stop_signal = signum;
switch(g_atomic_int_get(&stop)) {
case 0:
JANUS_PRINT("Stopping gateway, please wait...\n");
break;
case 1:
JANUS_PRINT("In a hurry? I'm trying to free resources cleanly, here!\n");
break;
default:
JANUS_PRINT("Ok, leaving immediately...\n");
break;
}
g_atomic_int_inc(&stop);
if(g_atomic_int_get(&stop) > 2)
exit(1);
}
/*! \brief Termination handler (atexit) */
static void janus_termination_handler(void) {
/* Free the instance name, if provided */
g_free(server_name);
/* Remove the PID file if we created it */
janus_pidfile_remove();
/* Close the logger */
janus_log_destroy();
/* If we're daemonizing, we send an error code to the parent */
if(daemonize) {
int code = 1;
ssize_t res = 0;
do {
res = write(pipefd[1], &code, sizeof(int));
} while(res == -1 && errno == EINTR);
}
}
/** @name Transport plugin callback interface
* These are the callbacks implemented by the gateway core, as part of
* the janus_transport_callbacks interface. Everything the transport
* plugins send the gateway is handled here.
*/
///@{
void janus_transport_incoming_request(janus_transport *plugin, void *transport, void *request_id, gboolean admin, json_t *message, json_error_t *error);
void janus_transport_gone(janus_transport *plugin, void *transport);
gboolean janus_transport_is_api_secret_needed(janus_transport *plugin);
gboolean janus_transport_is_api_secret_valid(janus_transport *plugin, const char *apisecret);
gboolean janus_transport_is_auth_token_needed(janus_transport *plugin);
gboolean janus_transport_is_auth_token_valid(janus_transport *plugin, const char *token);
void janus_transport_notify_event(janus_transport *plugin, void *transport, json_t *event);
static janus_transport_callbacks janus_handler_transport =
{
.incoming_request = janus_transport_incoming_request,
.transport_gone = janus_transport_gone,
.is_api_secret_needed = janus_transport_is_api_secret_needed,
.is_api_secret_valid = janus_transport_is_api_secret_valid,
.is_auth_token_needed = janus_transport_is_auth_token_needed,
.is_auth_token_valid = janus_transport_is_auth_token_valid,
.events_is_enabled = janus_events_is_enabled,
.notify_event = janus_transport_notify_event,
};
GThreadPool *tasks = NULL;
void janus_transport_task(gpointer data, gpointer user_data);
///@}
/** @name Plugin callback interface
* These are the callbacks implemented by the gateway core, as part of
* the janus_callbacks interface. Everything the plugins send the
* gateway is handled here.
*/
///@{
int janus_plugin_push_event(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *transaction, json_t *message, json_t *jsep);
json_t *janus_plugin_handle_sdp(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *sdp_type, const char *sdp);
void janus_plugin_relay_rtp(janus_plugin_session *plugin_session, int video, char *buf, int len);
void janus_plugin_relay_rtcp(janus_plugin_session *plugin_session, int video, char *buf, int len);
void janus_plugin_relay_data(janus_plugin_session *plugin_session, char *buf, int len);
void janus_plugin_close_pc(janus_plugin_session *plugin_session);
void janus_plugin_end_session(janus_plugin_session *plugin_session);
void janus_plugin_notify_event(janus_plugin *plugin, janus_plugin_session *plugin_session, json_t *event);
static janus_callbacks janus_handler_plugin =
{
.push_event = janus_plugin_push_event,
.relay_rtp = janus_plugin_relay_rtp,
.relay_rtcp = janus_plugin_relay_rtcp,
.relay_data = janus_plugin_relay_data,
.close_pc = janus_plugin_close_pc,
.end_session = janus_plugin_end_session,
.events_is_enabled = janus_events_is_enabled,
.notify_event = janus_plugin_notify_event,
};
///@}
/* Gateway Sessions */
static janus_mutex sessions_mutex;
static GHashTable *sessions = NULL, *old_sessions = NULL;
static GMainContext *sessions_watchdog_context = NULL;
static gboolean janus_cleanup_session(gpointer user_data) {
janus_session *session = (janus_session *) user_data;
JANUS_LOG(LOG_DBG, "Cleaning up session %"SCNu64"...\n", session->session_id);
janus_session_destroy(session->session_id);
return G_SOURCE_REMOVE;
}
static gboolean janus_check_sessions(gpointer user_data) {
if(session_timeout < 1) /* Session timeouts are disabled */
return G_SOURCE_CONTINUE;
GMainContext *watchdog_context = (GMainContext *) user_data;
janus_mutex_lock(&sessions_mutex);
if(sessions && g_hash_table_size(sessions) > 0) {
GHashTableIter iter;
gpointer value;
g_hash_table_iter_init(&iter, sessions);
while (g_hash_table_iter_next(&iter, NULL, &value)) {
janus_session *session = (janus_session *) value;
if (!session || session->destroy) {
continue;
}
gint64 now = janus_get_monotonic_time();
if (now - session->last_activity >= session_timeout * G_USEC_PER_SEC && !session->timeout) {
JANUS_LOG(LOG_INFO, "Timeout expired for session %"SCNu64"...\n", session->session_id);
/* Notify the transport */
if(session->source) {
json_t *event = json_object();
json_object_set_new(event, "janus", json_string("timeout"));
json_object_set_new(event, "session_id", json_integer(session->session_id));
/* Send this to the transport client */
session->source->transport->send_message(session->source->instance, NULL, FALSE, event);
/* Notify the transport plugin about the session timeout */
session->source->transport->session_over(session->source->instance, session->session_id, TRUE);
}
/* Notify event handlers as well */
if(janus_events_is_enabled())
janus_events_notify_handlers(JANUS_EVENT_TYPE_SESSION, session->session_id, "timeout", NULL);
/* Mark the session as over, we'll deal with it later */
session->timeout = 1;
/* FIXME Is this safe? apparently it causes hash table errors on the console */
g_hash_table_iter_remove(&iter);
g_hash_table_insert(old_sessions, janus_uint64_dup(session->session_id), session);
/* Schedule the session for deletion */
GSource *timeout_source = g_timeout_source_new_seconds(3);
g_source_set_callback(timeout_source, janus_cleanup_session, session, NULL);
g_source_attach(timeout_source, watchdog_context);
g_source_unref(timeout_source);
}
}
}
janus_mutex_unlock(&sessions_mutex);
return G_SOURCE_CONTINUE;
}
static gpointer janus_sessions_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(2);
g_source_set_callback(timeout_source, janus_check_sessions, watchdog_context, NULL);
g_source_attach(timeout_source, watchdog_context);
g_source_unref(timeout_source);
JANUS_LOG(LOG_INFO, "Sessions watchdog started\n");
g_main_loop_run(loop);
return NULL;
}
janus_session *janus_session_create(guint64 session_id) {
if(session_id == 0) {
while(session_id == 0) {
session_id = janus_random_uint64();
if(janus_session_find(session_id) != NULL) {
/* Session ID already taken, try another one */
session_id = 0;
}
}
}
JANUS_LOG(LOG_INFO, "Creating new session: %"SCNu64"\n", session_id);
janus_session *session = (janus_session *)g_malloc0(sizeof(janus_session));
if(session == NULL) {
JANUS_LOG(LOG_FATAL, "Memory error!\n");
return NULL;
}
session->session_id = session_id;
session->source = NULL;
session->destroy = 0;
session->timeout = 0;
session->last_activity = janus_get_monotonic_time();
janus_mutex_init(&session->mutex);
janus_mutex_lock(&sessions_mutex);
g_hash_table_insert(sessions, janus_uint64_dup(session->session_id), session);
janus_mutex_unlock(&sessions_mutex);
return session;
}
janus_session *janus_session_find(guint64 session_id) {
janus_mutex_lock(&sessions_mutex);
janus_session *session = g_hash_table_lookup(sessions, &session_id);
janus_mutex_unlock(&sessions_mutex);
return session;
}
janus_session *janus_session_find_destroyed(guint64 session_id) {
janus_mutex_lock(&sessions_mutex);
janus_session *session = g_hash_table_lookup(old_sessions, &session_id);
janus_mutex_unlock(&sessions_mutex);
return session;
}
void janus_session_notify_event(guint64 session_id, json_t *event) {
janus_mutex_lock(&sessions_mutex);
janus_session *session = sessions ? g_hash_table_lookup(sessions, &session_id) : NULL;
if(session != NULL && !session->destroy && session->source != NULL && session->source->transport != NULL) {
janus_mutex_unlock(&sessions_mutex);
/* Send this to the transport client */
JANUS_LOG(LOG_HUGE, "Sending event to %s (%p)\n", session->source->transport->get_package(), session->source->instance);
session->source->transport->send_message(session->source->instance, NULL, FALSE, event);
} else {
janus_mutex_unlock(&sessions_mutex);
/* No transport, free the event */
json_decref(event);
}
}
/* Destroys a session but does not remove it from the sessions hash table. */
gint janus_session_destroy(guint64 session_id) {
janus_session *session = janus_session_find_destroyed(session_id);
if(session == NULL) {
JANUS_LOG(LOG_ERR, "Couldn't find session to destroy: %"SCNu64"\n", session_id);
return -1;
}
JANUS_LOG(LOG_VERB, "Destroying session %"SCNu64"\n", session_id);
session->destroy = 1;
if (session->ice_handles != NULL && g_hash_table_size(session->ice_handles) > 0) {
GHashTableIter iter;
gpointer value;
/* Remove all handles */
g_hash_table_iter_init(&iter, session->ice_handles);
while (g_hash_table_iter_next(&iter, NULL, &value)) {
janus_ice_handle *handle = value;
if(!handle || g_atomic_int_get(&stop)) {
continue;
}
janus_ice_handle_destroy(session, handle->handle_id);
g_hash_table_iter_remove(&iter);
}
}
/* FIXME Actually destroy session */
janus_session_free(session);
return 0;
}
void janus_session_free(janus_session *session) {
if(session == NULL)
return;
janus_mutex_lock(&session->mutex);
if(session->ice_handles != NULL) {
g_hash_table_destroy(session->ice_handles);
session->ice_handles = NULL;
}
if(session->source != NULL) {
janus_request_destroy(session->source);
session->source = NULL;
}
janus_mutex_unlock(&session->mutex);
g_free(session);
session = NULL;
}
/* Requests management */
janus_request *janus_request_new(janus_transport *transport, void *instance, void *request_id, gboolean admin, json_t *message) {
janus_request *request = (janus_request *)g_malloc0(sizeof(janus_request));
request->transport = transport;
request->instance = instance;
request->request_id = request_id;
request->admin = admin;
request->message = message;
return request;
}
void janus_request_destroy(janus_request *request) {
if(request == NULL)
return;
request->transport = NULL;
request->instance = NULL;
request->request_id = NULL;
if(request->message)
json_decref(request->message);
request->message = NULL;
g_free(request);
}
int janus_process_incoming_request(janus_request *request) {
int ret = -1;
if(request == NULL) {
JANUS_LOG(LOG_ERR, "Missing request or payload to process, giving up...\n");
return ret;
}
int error_code = 0;
char error_cause[100];
json_t *root = request->message;
/* Ok, let's start with the ids */
guint64 session_id = 0, handle_id = 0;
json_t *s = json_object_get(root, "session_id");
if(s && json_is_integer(s))
session_id = json_integer_value(s);
json_t *h = json_object_get(root, "handle_id");
if(h && json_is_integer(h))
handle_id = json_integer_value(h);
/* Get transaction and message request */
JANUS_VALIDATE_JSON_OBJECT(root, incoming_request_parameters,
error_code, error_cause, FALSE,
JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
if(error_code != 0) {
ret = janus_process_error_string(request, session_id, NULL, error_code, error_cause);
goto jsondone;
}
json_t *transaction = json_object_get(root, "transaction");
const gchar *transaction_text = json_string_value(transaction);
json_t *message = json_object_get(root, "janus");
const gchar *message_text = json_string_value(message);
if(session_id == 0 && handle_id == 0) {
/* Can only be a 'Create new session', a 'Get info' or a 'Ping/Pong' request */
if(!strcasecmp(message_text, "info")) {
ret = janus_process_success(request, janus_info(transaction_text));
goto jsondone;
}
if(!strcasecmp(message_text, "ping")) {
/* Prepare JSON reply */
json_t *reply = json_object();
json_object_set_new(reply, "janus", json_string("pong"));
json_object_set_new(reply, "transaction", json_string(transaction_text));
ret = janus_process_success(request, reply);
goto jsondone;
}
if(strcasecmp(message_text, "create")) {
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
goto jsondone;
}
/* Any secret/token to check? */
gboolean secret_authorized = FALSE, token_authorized = FALSE;
if(api_secret == NULL && !janus_auth_is_enabled()) {
/* Nothing to check */
secret_authorized = TRUE;
token_authorized = TRUE;
} else {
if(api_secret != NULL) {
/* There's an API secret, check that the client provided it */
json_t *secret = json_object_get(root, "apisecret");
if(secret && json_is_string(secret) && janus_strcmp_const_time(json_string_value(secret), api_secret)) {
secret_authorized = TRUE;
}
}
if(janus_auth_is_enabled()) {
/* The token based authentication mechanism is enabled, check that the client provided it */
json_t *token = json_object_get(root, "token");
if(token && json_is_string(token) && janus_auth_check_token(json_string_value(token))) {
token_authorized = TRUE;
}
}
/* We consider a request authorized if either the proper API secret or a valid token has been provided */
if(!secret_authorized && !token_authorized) {
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNAUTHORIZED, NULL);
goto jsondone;
}
}
session_id = 0;
json_t *id = json_object_get(root, "id");
if(id != NULL) {
/* The application provided the session ID to use */
session_id = json_integer_value(id);
if(session_id > 0 && janus_session_find(session_id) != NULL) {
/* Session ID already taken */
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_CONFLICT, "Session ID already in use");
goto jsondone;
}
}
/* Handle it */
janus_session *session = janus_session_create(session_id);
if(session == NULL) {
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN, "Memory error");
goto jsondone;
}
session_id = session->session_id;
/* Take note of the request source that originated this session (HTTP, WebSockets, RabbitMQ?) */
session->source = janus_request_new(request->transport, request->instance, NULL, FALSE, NULL);
/* Notify the source that a new session has been created */
request->transport->session_created(request->instance, session->session_id);
/* Notify event handlers */
if(janus_events_is_enabled()) {
/* Session created, add info on the transport that originated it */
json_t *transport = json_object();
json_object_set_new(transport, "transport", json_string(session->source->transport->get_package()));
char id[32];
memset(id, 0, sizeof(id));
g_snprintf(id, sizeof(id), "%p", session->source->instance);
json_object_set_new(transport, "id", json_string(id));
janus_events_notify_handlers(JANUS_EVENT_TYPE_SESSION, session_id, "created", transport);
}
/* Prepare JSON reply */
json_t *reply = json_object();
json_object_set_new(reply, "janus", json_string("success"));
json_object_set_new(reply, "transaction", json_string(transaction_text));
json_t *data = json_object();
json_object_set_new(data, "id", json_integer(session_id));
json_object_set_new(reply, "data", data);
/* Send the success reply */
ret = janus_process_success(request, reply);
goto jsondone;
}
if(session_id < 1) {
JANUS_LOG(LOG_ERR, "Invalid session\n");
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, NULL);
goto jsondone;
}
if(h && handle_id < 1) {
JANUS_LOG(LOG_ERR, "Invalid handle\n");
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, NULL);
goto jsondone;
}
/* Go on with the processing */
gboolean secret_authorized = FALSE, token_authorized = FALSE;
if(api_secret == NULL && !janus_auth_is_enabled()) {
/* Nothing to check */
secret_authorized = TRUE;
token_authorized = TRUE;
} else {
if(api_secret != NULL) {
/* There's an API secret, check that the client provided it */
json_t *secret = json_object_get(root, "apisecret");
if(secret && json_is_string(secret) && janus_strcmp_const_time(json_string_value(secret), api_secret)) {
secret_authorized = TRUE;
}
}
if(janus_auth_is_enabled()) {
/* The token based authentication mechanism is enabled, check that the client provided it */
json_t *token = json_object_get(root, "token");
if(token && json_is_string(token) && janus_auth_check_token(json_string_value(token))) {
token_authorized = TRUE;
}
}
/* We consider a request authorized if either the proper API secret or a valid token has been provided */
if(!secret_authorized && !token_authorized) {
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNAUTHORIZED, NULL);
goto jsondone;
}
}
/* If we got here, make sure we have a session (and/or a handle) */
janus_session *session = janus_session_find(session_id);
if(!session) {
JANUS_LOG(LOG_ERR, "Couldn't find any session %"SCNu64"...\n", session_id);
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, "No such session %"SCNu64"", session_id);
goto jsondone;
}
/* Update the last activity timer */
session->last_activity = janus_get_monotonic_time();
janus_ice_handle *handle = NULL;
if(handle_id > 0) {
handle = janus_ice_handle_find(session, handle_id);
if(!handle) {
JANUS_LOG(LOG_ERR, "Couldn't find any handle %"SCNu64" in session %"SCNu64"...\n", handle_id, session_id);
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_HANDLE_NOT_FOUND, "No such handle %"SCNu64" in session %"SCNu64"", handle_id, session_id);
goto jsondone;
}
}
/* What is this? */
if(!strcasecmp(message_text, "keepalive")) {
/* Just a keep-alive message, reply with an ack */
JANUS_LOG(LOG_VERB, "Got a keep-alive on session %"SCNu64"\n", session_id);
json_t *reply = json_object();
json_object_set_new(reply, "janus", json_string("ack"));
json_object_set_new(reply, "session_id", json_integer(session_id));
json_object_set_new(reply, "transaction", json_string(transaction_text));
/* Send the success reply */
ret = janus_process_success(request, reply);
} else if(!strcasecmp(message_text, "attach")) {
if(handle != NULL) {
/* Attach is a session-level command */
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
goto jsondone;
}
JANUS_VALIDATE_JSON_OBJECT(root, attach_parameters,
error_code, error_cause, FALSE,
JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
if(error_code != 0) {
ret = janus_process_error_string(request, session_id, NULL, error_code, error_cause);
goto jsondone;
}
json_t *plugin = json_object_get(root, "plugin");
const gchar *plugin_text = json_string_value(plugin);
janus_plugin *plugin_t = janus_plugin_find(plugin_text);
if(plugin_t == NULL) {
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_NOT_FOUND, "No such plugin '%s'", plugin_text);
goto jsondone;
}
/* If the auth token mechanism is enabled, we should check if this token can access this plugin */
if(janus_auth_is_enabled()) {
json_t *token = json_object_get(root, "token");
if(token != NULL) {
const char *token_value = json_string_value(token);
if(token_value && !janus_auth_check_plugin(token_value, plugin_t)) {
JANUS_LOG(LOG_ERR, "Token '%s' can't access plugin '%s'\n", token_value, plugin_text);
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNAUTHORIZED_PLUGIN, "Provided token can't access plugin '%s'", plugin_text);
goto jsondone;
}
}
}
json_t *opaque = json_object_get(root, "opaque_id");
const char *opaque_id = opaque ? json_string_value(opaque) : NULL;
/* Create handle */
handle = janus_ice_handle_create(session, opaque_id);
if(handle == NULL) {
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN, "Memory error");
goto jsondone;
}
handle_id = handle->handle_id;
/* Attach to the plugin */
int error = 0;
if((error = janus_ice_handle_attach_plugin(session, handle_id, plugin_t)) != 0) {
/* TODO Make error struct to pass verbose information */
janus_ice_handle_destroy(session, handle_id);
janus_mutex_lock(&session->mutex);
g_hash_table_remove(session->ice_handles, &handle_id);
janus_mutex_unlock(&session->mutex);
JANUS_LOG(LOG_ERR, "Couldn't attach to plugin '%s', error '%d'\n", plugin_text, error);
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_ATTACH, "Couldn't attach to plugin: error '%d'", error);
goto jsondone;
}
/* Prepare JSON reply */
json_t *reply = json_object();
json_object_set_new(reply, "janus", json_string("success"));
json_object_set_new(reply, "session_id", json_integer(session_id));
json_object_set_new(reply, "transaction", json_string(transaction_text));
json_t *data = json_object();
json_object_set_new(data, "id", json_integer(handle_id));
json_object_set_new(reply, "data", data);
/* Send the success reply */
ret = janus_process_success(request, reply);
} else if(!strcasecmp(message_text, "destroy")) {
if(handle != NULL) {
/* Query is a session-level command */
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
goto jsondone;
}
/* Schedule the session for deletion */
session->destroy = 1;
janus_mutex_lock(&sessions_mutex);
g_hash_table_remove(sessions, &session->session_id);
g_hash_table_insert(old_sessions, janus_uint64_dup(session->session_id), session);
GSource *timeout_source = g_timeout_source_new_seconds(3);
g_source_set_callback(timeout_source, janus_cleanup_session, session, NULL);
g_source_attach(timeout_source, sessions_watchdog_context);
g_source_unref(timeout_source);
janus_mutex_unlock(&sessions_mutex);
/* Notify the source that the session has been destroyed */
if(session->source && session->source->transport)
session->source->transport->session_over(session->source->instance, session->session_id, FALSE);
/* Prepare JSON reply */
json_t *reply = json_object();
json_object_set_new(reply, "janus", json_string("success"));
json_object_set_new(reply, "session_id", json_integer(session_id));
json_object_set_new(reply, "transaction", json_string(transaction_text));
/* Send the success reply */
ret = janus_process_success(request, reply);
/* Notify event handlers as well */
if(janus_events_is_enabled())
janus_events_notify_handlers(JANUS_EVENT_TYPE_SESSION, session_id, "destroyed", NULL);
} else if(!strcasecmp(message_text, "detach")) {
if(handle == NULL) {
/* Query is an handle-level command */
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
goto jsondone;
}
if(handle->app == NULL || handle->app_handle == NULL) {
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_DETACH, "No plugin to detach from");
goto jsondone;
}
int error = janus_ice_handle_destroy(session, handle_id);
janus_mutex_lock(&session->mutex);
g_hash_table_remove(session->ice_handles, &handle_id);
janus_mutex_unlock(&session->mutex);
if(error != 0) {
/* TODO Make error struct to pass verbose information */
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_DETACH, "Couldn't detach from plugin: error '%d'", error);
/* TODO Delete handle instance */
goto jsondone;
}
/* Prepare JSON reply */
json_t *reply = json_object();
json_object_set_new(reply, "janus", json_string("success"));
json_object_set_new(reply, "session_id", json_integer(session_id));
json_object_set_new(reply, "transaction", json_string(transaction_text));
/* Send the success reply */
ret = janus_process_success(request, reply);
} else if(!strcasecmp(message_text, "hangup")) {
if(handle == NULL) {
/* Query is an handle-level command */
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
goto jsondone;
}
if(handle->app == NULL || handle->app_handle == NULL) {
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_DETACH, "No plugin attached");
goto jsondone;
}
janus_ice_webrtc_hangup(handle);
/* Prepare JSON reply */
json_t *reply = json_object();
json_object_set_new(reply, "janus", json_string("success"));
json_object_set_new(reply, "session_id", json_integer(session_id));
json_object_set_new(reply, "transaction", json_string(transaction_text));
/* Send the success reply */
ret = janus_process_success(request, reply);
} else if(!strcasecmp(message_text, "message")) {
if(handle == NULL) {
/* Query is an handle-level command */
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
goto jsondone;
}
if(handle->app == NULL || handle->app_handle == NULL) {
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE, "No plugin to handle this message");
goto jsondone;
}
janus_plugin *plugin_t = (janus_plugin *)handle->app;
JANUS_LOG(LOG_VERB, "[%"SCNu64"] There's a message for %s\n", handle->handle_id, plugin_t->get_name());
JANUS_VALIDATE_JSON_OBJECT(root, body_parameters,
error_code, error_cause, FALSE,
JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
if(error_code != 0) {
ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
goto jsondone;
}
json_t *body = json_object_get(root, "body");
/* Is there an SDP attached? */
json_t *jsep = json_object_get(root, "jsep");
char *jsep_type = NULL;
char *jsep_sdp = NULL, *jsep_sdp_stripped = NULL;
if(jsep != NULL) {
if(!json_is_object(jsep)) {
ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_JSON_OBJECT, "Invalid jsep object");
goto jsondone;
}
JANUS_VALIDATE_JSON_OBJECT_FORMAT("JSEP error: missing mandatory element (%s)",
"JSEP error: invalid element type (%s should be %s)",
jsep, jsep_parameters, error_code, error_cause, FALSE,
JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
if(error_code != 0) {
ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
goto jsondone;
}
json_t *type = json_object_get(jsep, "type");
jsep_type = g_strdup(json_string_value(type));
type = NULL;
gboolean do_trickle = TRUE;
json_t *jsep_trickle = json_object_get(jsep, "trickle");
do_trickle = jsep_trickle ? json_is_true(jsep_trickle) : TRUE;
/* Are we still cleaning up from a previous media session? */
if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_CLEANING)) {
JANUS_LOG(LOG_VERB, "[%"SCNu64"] Still cleaning up from a previous media session, let's wait a bit...\n", handle->handle_id);
gint64 waited = 0;
while(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_CLEANING)) {
g_usleep(100000);
waited += 100000;
if(waited >= 3*G_USEC_PER_SEC) {
JANUS_LOG(LOG_VERB, "[%"SCNu64"] -- Waited 3 seconds, that's enough!\n", handle->handle_id);
break;
}
}
}
/* Check the JSEP type */
janus_mutex_lock(&handle->mutex);
int offer = 0;
if(!strcasecmp(jsep_type, "offer")) {
offer = 1;
janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_OFFER);
janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_ANSWER);
} else if(!strcasecmp(jsep_type, "answer")) {
janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_ANSWER);