forked from meetecho/janus-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
janus.c
5273 lines (5106 loc) · 210 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 implements the transports (HTTP, WebSockets, RabbitMQ) and Janus
* protocol (a JSON-based protocol implemented) to interact with the web
* applications. The core also takes care of bridging peers and plugins
* accordingly.
*
* \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/socket.h>
#include "janus.h"
#include "cmdline.h"
#include "config.h"
#include "apierror.h"
#include "debug.h"
#include "rtcp.h"
#include "sdp.h"
#include "utils.h"
#define JANUS_NAME "Janus WebRTC Gateway"
#define JANUS_AUTHOR "Meetecho s.r.l."
#define JANUS_VERSION 9
#define JANUS_VERSION_STRING "0.0.9"
#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 *plugins = NULL;
static GHashTable *plugins_so = NULL;
/* MHD Web Server */
static struct MHD_Daemon *ws = NULL, *sws = NULL;
static char *ws_path = NULL;
static char *ws_api_secret = NULL;
#ifdef HAVE_WEBSOCKETS
/* libwebsockets WS context(s) */
static struct libwebsocket_context *wss = NULL, *swss = NULL;
/* libwebsockets sessions that have been closed */
static GList *old_wss;
static janus_mutex old_wss_mutex;
/* Callback for HTTP-related events (automatically rejected) */
static int janus_wss_callback_http(struct libwebsocket_context *this,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason,
void *user, void *in, size_t len);
/* Callback for WebSockets-related events */
static int janus_wss_callback(struct libwebsocket_context *this,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason,
void *user, void *in, size_t len);
/* Protocol mapping */
static struct libwebsocket_protocols wss_protocols[] = {
{ "http-only", janus_wss_callback_http, 0, 0 },
{ "janus-protocol", janus_wss_callback, sizeof(janus_websocket_client), 0 },
{ NULL, NULL, 0 }
};
/* Helper for debugging reasons */
const char *janus_wss_reason_string(enum libwebsocket_callback_reasons reason);
#endif
#ifdef HAVE_RABBITMQ
/* RabbitMQ support */
amqp_connection_state_t rmq_conn = NULL;
amqp_channel_t rmq_channel = 0;
amqp_bytes_t to_janus_queue, from_janus_queue;
#endif
/* Admin/Monitor MHD Web Server */
static struct MHD_Daemon *admin_ws = NULL, *admin_sws = NULL;
static char *admin_ws_path = NULL;
static char *admin_ws_api_secret = NULL;
/* Admin/Monitor ACL list */
GList *janus_admin_access_list = NULL;
janus_mutex access_list_mutex;
void janus_admin_allow_address(const char *ip);
void janus_admin_allow_address(const char *ip) {
if(ip == NULL)
return;
/* Is this an IP or an interface? */
janus_mutex_lock(&access_list_mutex);
janus_admin_access_list = g_list_append(janus_admin_access_list, (gpointer)ip);
janus_mutex_unlock(&access_list_mutex);
}
gboolean janus_admin_is_allowed(const char *ip);
gboolean janus_admin_is_allowed(const char *ip) {
if(ip == NULL)
return FALSE;
if(janus_admin_access_list == NULL)
return TRUE;
janus_mutex_lock(&access_list_mutex);
GList *temp = janus_admin_access_list;
while(temp) {
const char *allowed = (const char *)temp->data;
if(allowed != NULL && strstr(ip, allowed)) {
janus_mutex_unlock(&access_list_mutex);
return TRUE;
}
temp = temp->next;
}
janus_mutex_unlock(&access_list_mutex);
return FALSE;
}
/* Admin/Monitor helpers */
json_t *janus_admin_stream_summary(janus_ice_stream *stream);
json_t *janus_admin_component_summary(janus_ice_component *component);
/* Certificates */
static char *server_pem = NULL;
gchar *janus_get_server_pem(void) {
return server_pem;
}
static char *server_key = NULL;
gchar *janus_get_server_key(void) {
return server_key;
}
/* Information */
char *janus_info(const char *transaction);
char *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));
#ifdef HAVE_SCTP
json_object_set_new(info, "data_channels", json_string("true"));
#else
json_object_set_new(info, "data_channels", json_string("false"));
#endif
#ifdef HAVE_WEBSOCKETS
json_object_set_new(info, "websockets", json_string("true"));
#else
json_object_set_new(info, "websockets", json_string("false"));
#endif
#ifdef HAVE_RABBITMQ
json_object_set_new(info, "rabbitmq", json_string("true"));
#else
json_object_set_new(info, "rabbitmq", json_string("false"));
#endif
json_object_set_new(info, "ipv6", json_string(janus_ice_is_ipv6_enabled() ? "true" : "false"));
json_object_set_new(info, "ice-tcp", json_string(janus_ice_is_ice_tcp_enabled() ? "true" : "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_t *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(data, p->get_package(), plugin);
}
}
json_object_set_new(info, "plugins", data);
/* Convert to a string */
char *info_text = json_dumps(info, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
json_decref(info);
return info_text;
}
static gchar local_ip[INET6_ADDRSTRLEN];
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) {
if(ip == NULL)
return;
if(public_ip != NULL)
g_free(public_ip);
public_ip = g_strdup(ip);
}
static volatile gint stop = 0;
gint janus_is_stopping(void) {
return g_atomic_int_get(&stop);
}
/* Logging */
int janus_log_level = 0;
gboolean janus_log_timestamps = FALSE;
gboolean janus_log_colors = FALSE;
int lock_debug = 0;
/*! \brief Signal handler (just used to intercept CTRL+C) */
void janus_handle_signal(int signum);
void janus_handle_signal(int 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);
}
/** @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_push_event(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *transaction, const char *message, const char *sdp_type, const char *sdp);
json_t *janus_handle_sdp(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *sdp_type, const char *sdp);
void janus_relay_rtp(janus_plugin_session *plugin_session, int video, char *buf, int len);
void janus_relay_rtcp(janus_plugin_session *plugin_session, int video, char *buf, int len);
void janus_relay_data(janus_plugin_session *plugin_session, char *buf, int len);
void janus_close_pc(janus_plugin_session *plugin_session);
void janus_end_session(janus_plugin_session *plugin_session);
static janus_callbacks janus_handler_plugin =
{
.push_event = janus_push_event,
.relay_rtp = janus_relay_rtp,
.relay_rtcp = janus_relay_rtcp,
.relay_data = janus_relay_data,
.close_pc = janus_close_pc,
.end_session = janus_end_session,
};
///@}
#ifdef HAVE_RABBITMQ
/* FIXME RabbitMQ session (always 1 at the moment) */
janus_rabbitmq_client *rmq_client = NULL;
#endif
/* Gateway Sessions */
static janus_mutex sessions_mutex;
static GHashTable *sessions = NULL, *old_sessions = NULL;
static GMainContext *sessions_watchdog_context = NULL;
#define SESSION_TIMEOUT 60 /* FIXME Should this be higher, e.g., 120 seconds? */
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) {
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);
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));
gchar *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
json_decref(event);
janus_http_event *notification = calloc(1, sizeof(janus_http_event));
notification->code = 200;
notification->payload = event_text;
notification->allocated = 1;
g_async_queue_push(session->messages, notification);
#ifdef HAVE_WEBSOCKETS
janus_request_source *source = (janus_request_source *)session->source;
if(source != NULL && source->type == JANUS_SOURCE_WEBSOCKETS) {
/* Send this as soon as the WebSocket becomes writeable */
janus_websocket_client *client = (janus_websocket_client *)source->source;
/* Make sure this is not related to a closed WebSocket session */
janus_mutex_lock(&old_wss_mutex);
if(g_list_find(old_wss, client) == NULL) {
janus_mutex_lock(&client->mutex);
libwebsocket_callback_on_writable(client->context, client->wsi);
janus_mutex_unlock(&client->mutex);
}
janus_mutex_unlock(&old_wss_mutex);
}
#endif
session->timeout = 1;
g_hash_table_iter_remove(&iter);
g_hash_table_insert(old_sessions, GUINT_TO_POINTER(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 = g_random_int();
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 *)calloc(1, sizeof(janus_session));
if(session == NULL) {
JANUS_LOG(LOG_FATAL, "Memory error!\n");
return NULL;
}
session->session_id = session_id;
session->messages = g_async_queue_new_full((GDestroyNotify) janus_http_event_free);
session->destroy = 0;
session->last_activity = janus_get_monotonic_time();
janus_mutex_init(&session->mutex);
janus_mutex_lock(&sessions_mutex);
g_hash_table_insert(sessions, GUINT_TO_POINTER(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, GUINT_TO_POINTER(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, GUINT_TO_POINTER(session_id));
janus_mutex_unlock(&sessions_mutex);
return session;
}
void janus_session_notify_event(guint64 session_id, janus_http_event *event) {
janus_mutex_lock(&sessions_mutex);
janus_session *session = g_hash_table_lookup(sessions, GUINT_TO_POINTER(session_id));
janus_mutex_unlock(&sessions_mutex);
if(session != NULL) {
g_async_queue_push(session->messages, event);
#ifdef HAVE_WEBSOCKETS
janus_request_source *source = (janus_request_source *)session->source;
if(source != NULL && source->type == JANUS_SOURCE_WEBSOCKETS) {
/* Send this as soon as the WebSocket becomes writeable */
janus_websocket_client *client = (janus_websocket_client *)source->source;
/* Make sure this is not related to a closed WebSocket session */
janus_mutex_lock(&old_wss_mutex);
if(g_list_find(old_wss, client) == NULL) {
janus_mutex_lock(&client->mutex);
libwebsocket_callback_on_writable(client->context, client->wsi);
janus_mutex_unlock(&client->mutex);
}
janus_mutex_unlock(&old_wss_mutex);
}
#endif
}
}
/* 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->messages != NULL) {
g_async_queue_unref(session->messages);
session->messages = NULL;
}
janus_request_source *source = (janus_request_source *)session->source;
if(source != NULL) {
janus_request_source_destroy(source);
session->source = NULL;
}
janus_mutex_unlock(&session->mutex);
g_free(session);
session = NULL;
}
/* Connection notifiers */
int janus_ws_client_connect(void *cls, const struct sockaddr *addr, socklen_t addrlen) {
struct sockaddr_in *sin = (struct sockaddr_in *)addr;
char *ip = inet_ntoa(sin->sin_addr);
JANUS_LOG(LOG_HUGE, "New connection on REST API: %s\n", ip);
/* TODO Implement access limitation based on IP addresses */
return MHD_YES;
}
int janus_admin_ws_client_connect(void *cls, const struct sockaddr *addr, socklen_t addrlen) {
struct sockaddr_in *sin = (struct sockaddr_in *)addr;
char *ip = inet_ntoa(sin->sin_addr);
JANUS_LOG(LOG_HUGE, "New connection on admin/monitor: %s\n", ip);
/* Any access limitation based on this IP address? */
if(!janus_admin_is_allowed(ip)) {
JANUS_LOG(LOG_ERR, "IP %s is unauthorized to connect to the admin/monitor interface\n", ip);
return MHD_NO;
}
return MHD_YES;
}
/* WebServer requests handler */
int janus_ws_handler(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **ptr)
{
char *payload = NULL;
struct MHD_Response *response = NULL;
int ret = MHD_NO;
gchar *session_path = NULL, *handle_path = NULL;
gchar **basepath = NULL, **path = NULL;
/* Is this the first round? */
int firstround = 0;
janus_http_msg *msg = (janus_http_msg *)*ptr;
if (msg == NULL) {
firstround = 1;
JANUS_LOG(LOG_VERB, "Got a HTTP %s request on %s...\n", method, url);
JANUS_LOG(LOG_DBG, " ... Just parsing headers for now...\n");
msg = calloc(1, sizeof(janus_http_msg));
if(msg == NULL) {
JANUS_LOG(LOG_FATAL, "Memory error!\n");
ret = MHD_queue_response(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response);
MHD_destroy_response(response);
goto done;
}
msg->acrh = NULL;
msg->acrm = NULL;
msg->payload = NULL;
msg->len = 0;
msg->session_id = 0;
*ptr = msg;
MHD_get_connection_values(connection, MHD_HEADER_KIND, &janus_ws_headers, msg);
ret = MHD_YES;
} else {
JANUS_LOG(LOG_DBG, "Processing HTTP %s request on %s...\n", method, url);
}
/* Parse request */
if (strcasecmp(method, "GET") && strcasecmp(method, "POST") && strcasecmp(method, "OPTIONS")) {
JANUS_LOG(LOG_ERR, "Unsupported method...\n");
response = MHD_create_response_from_data(0, NULL, MHD_NO, MHD_NO);
MHD_add_response_header(response, "Access-Control-Allow-Origin", "*");
if(msg->acrm)
MHD_add_response_header(response, "Access-Control-Allow-Methods", msg->acrm);
if(msg->acrh)
MHD_add_response_header(response, "Access-Control-Allow-Headers", msg->acrh);
ret = MHD_queue_response(connection, MHD_HTTP_NOT_IMPLEMENTED, response);
MHD_destroy_response(response);
return ret;
}
if (!strcasecmp(method, "OPTIONS")) {
response = MHD_create_response_from_data(0, NULL, MHD_NO, MHD_NO);
MHD_add_response_header(response, "Access-Control-Allow-Origin", "*");
if(msg->acrm)
MHD_add_response_header(response, "Access-Control-Allow-Methods", msg->acrm);
if(msg->acrh)
MHD_add_response_header(response, "Access-Control-Allow-Headers", msg->acrh);
ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
MHD_destroy_response(response);
}
/* Get path components */
if(strcasecmp(url, ws_path)) {
if(strlen(ws_path) > 1) {
basepath = g_strsplit(url, ws_path, -1);
} else {
/* The base path is the web server too itself, we process the url itself */
basepath = calloc(3, sizeof(char *));
basepath[0] = g_strdup("/");
basepath[1] = g_strdup(url);
}
if(basepath[0] == NULL || basepath[1] == NULL || basepath[1][0] != '/') {
JANUS_LOG(LOG_ERR, "Invalid url %s\n", url);
response = MHD_create_response_from_data(0, NULL, MHD_NO, MHD_NO);
MHD_add_response_header(response, "Access-Control-Allow-Origin", "*");
if(msg->acrm)
MHD_add_response_header(response, "Access-Control-Allow-Methods", msg->acrm);
if(msg->acrh)
MHD_add_response_header(response, "Access-Control-Allow-Headers", msg->acrh);
ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response);
MHD_destroy_response(response);
}
if(firstround) {
g_strfreev(basepath);
return ret;
}
path = g_strsplit(basepath[1], "/", -1);
if(path == NULL || path[1] == NULL) {
JANUS_LOG(LOG_ERR, "Invalid path %s (%s)\n", basepath[1], path[1]);
response = MHD_create_response_from_data(0, NULL, MHD_NO, MHD_NO);
MHD_add_response_header(response, "Access-Control-Allow-Origin", "*");
if(msg->acrm)
MHD_add_response_header(response, "Access-Control-Allow-Methods", msg->acrm);
if(msg->acrh)
MHD_add_response_header(response, "Access-Control-Allow-Headers", msg->acrh);
ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response);
MHD_destroy_response(response);
}
}
if(firstround)
return ret;
JANUS_LOG(LOG_DBG, " ... parsing request...\n");
if(path != NULL && path[1] != NULL && strlen(path[1]) > 0) {
session_path = g_strdup(path[1]);
if(session_path == NULL) {
JANUS_LOG(LOG_FATAL, "Memory error!\n");
ret = MHD_queue_response(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response);
MHD_destroy_response(response);
goto done;
}
JANUS_LOG(LOG_HUGE, "Session: %s\n", session_path);
}
if(session_path != NULL && path[2] != NULL && strlen(path[2]) > 0) {
handle_path = g_strdup(path[2]);
if(handle_path == NULL) {
JANUS_LOG(LOG_FATAL, "Memory error!\n");
ret = MHD_queue_response(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response);
MHD_destroy_response(response);
goto done;
}
JANUS_LOG(LOG_HUGE, "Handle: %s\n", handle_path);
}
if(session_path != NULL && handle_path != NULL && path[3] != NULL && strlen(path[3]) > 0) {
JANUS_LOG(LOG_ERR, "Too many components...\n");
response = MHD_create_response_from_data(0, NULL, MHD_NO, MHD_NO);
MHD_add_response_header(response, "Access-Control-Allow-Origin", "*");
if(msg->acrm)
MHD_add_response_header(response, "Access-Control-Allow-Methods", msg->acrm);
if(msg->acrh)
MHD_add_response_header(response, "Access-Control-Allow-Headers", msg->acrh);
ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response);
MHD_destroy_response(response);
goto done;
}
/* Get payload, if any */
if(!strcasecmp(method, "POST")) {
JANUS_LOG(LOG_HUGE, "Processing POST data (%s) (%zu bytes)...\n", msg->contenttype, *upload_data_size);
if(*upload_data_size != 0) {
if(msg->payload == NULL)
msg->payload = calloc(1, *upload_data_size+1);
else
msg->payload = realloc(msg->payload, msg->len+*upload_data_size+1);
if(msg->payload == NULL) {
JANUS_LOG(LOG_FATAL, "Memory error!\n");
ret = MHD_queue_response(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response);
MHD_destroy_response(response);
goto done;
}
memcpy(msg->payload+msg->len, upload_data, *upload_data_size);
msg->len += *upload_data_size;
memset(msg->payload + msg->len, '\0', 1);
JANUS_LOG(LOG_DBG, " -- Data we have now (%zu bytes)\n", msg->len);
*upload_data_size = 0; /* Go on */
ret = MHD_YES;
goto done;
}
JANUS_LOG(LOG_DBG, "Done getting payload, we can answer\n");
if(msg->payload == NULL) {
JANUS_LOG(LOG_ERR, "No payload :-(\n");
ret = MHD_NO;
goto done;
}
payload = msg->payload;
JANUS_LOG(LOG_HUGE, "%s\n", payload);
}
/* Process the request, specifying this HTTP connection is the source */
janus_request_source source = {
.type = JANUS_SOURCE_PLAIN_HTTP,
.source = (void *)connection,
.msg = (void *)msg,
};
/* Is this a generic request for info? */
if(session_path != NULL && !strcmp(session_path, "info")) {
/* The info REST endpoint, if contacted through a GET, provides information on the gateway */
if(strcasecmp(method, "GET")) {
ret = janus_process_error(&source, 0, NULL, JANUS_ERROR_USE_GET, "Use GET for the info endpoint");
goto done;
}
/* Send the success reply */
ret = janus_process_success(&source, janus_info(NULL));
goto done;
}
/* Or maybe a long poll */
if(!strcasecmp(method, "GET") || !payload) {
guint64 session_id = session_path ? g_ascii_strtoll(session_path, NULL, 10) : 0;
if(session_id < 1) {
JANUS_LOG(LOG_ERR, "Invalid session %s\n", session_path);
response = MHD_create_response_from_data(0, NULL, MHD_NO, MHD_NO);
MHD_add_response_header(response, "Access-Control-Allow-Origin", "*");
if(msg->acrm)
MHD_add_response_header(response, "Access-Control-Allow-Methods", msg->acrm);
if(msg->acrh)
MHD_add_response_header(response, "Access-Control-Allow-Headers", msg->acrh);
ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response);
MHD_destroy_response(response);
goto done;
}
msg->session_id = session_id;
if(handle_path) {
char *location = (char *)calloc(strlen(ws_path) + strlen(session_path) + 2, sizeof(char));
g_sprintf(location, "%s/%s", ws_path, session_path);
JANUS_LOG(LOG_ERR, "Invalid GET to %s, redirecting to %s\n", url, location);
response = MHD_create_response_from_data(0, NULL, MHD_NO, MHD_NO);
MHD_add_response_header(response, "Location", location);
MHD_add_response_header(response, "Access-Control-Allow-Origin", "*");
if(msg->acrm)
MHD_add_response_header(response, "Access-Control-Allow-Methods", msg->acrm);
if(msg->acrh)
MHD_add_response_header(response, "Access-Control-Allow-Headers", msg->acrh);
ret = MHD_queue_response(connection, 302, response);
MHD_destroy_response(response);
g_free(location);
goto done;
}
janus_session *session = janus_session_find(session_id);
if(!session) {
JANUS_LOG(LOG_ERR, "Couldn't find any session %"SCNu64"...\n", session_id);
response = MHD_create_response_from_data(0, NULL, MHD_NO, MHD_NO);
MHD_add_response_header(response, "Access-Control-Allow-Origin", "*");
if(msg->acrm)
MHD_add_response_header(response, "Access-Control-Allow-Methods", msg->acrm);
if(msg->acrh)
MHD_add_response_header(response, "Access-Control-Allow-Headers", msg->acrh);
ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response);
MHD_destroy_response(response);
goto done;
}
if(ws_api_secret != NULL) {
/* There's an API secret, check that the client provided it */
const char *secret = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "apisecret");
if(!secret || !janus_strcmp_const_time(secret, ws_api_secret)) {
response = MHD_create_response_from_data(0, NULL, MHD_NO, MHD_NO);
MHD_add_response_header(response, "Access-Control-Allow-Origin", "*");
if(msg->acrm)
MHD_add_response_header(response, "Access-Control-Allow-Methods", msg->acrm);
if(msg->acrh)
MHD_add_response_header(response, "Access-Control-Allow-Headers", msg->acrh);
ret = MHD_queue_response(connection, MHD_HTTP_FORBIDDEN, response);
MHD_destroy_response(response);
goto done;
}
}
/* Update the last activity timer */
session->last_activity = janus_get_monotonic_time();
/* How many messages can we send back in a single response? (just one by default) */
int max_events = 1;
const char *maxev = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "maxev");
if(maxev != NULL) {
max_events = atoi(maxev);
if(max_events < 1) {
JANUS_LOG(LOG_WARN, "Invalid maxev parameter passed (%d), defaulting to 1\n", max_events);
max_events = 1;
}
}
JANUS_LOG(LOG_VERB, "Session %"SCNu64" found... returning up to %d messages\n", session->session_id, max_events);
/* Handle GET, taking the first message from the list */
janus_http_event *event = g_async_queue_try_pop(session->messages);
if(event != NULL) {
if(max_events == 1) {
/* Return just this message and leave */
ret = janus_process_success(&source, event->payload);
} else {
/* The application is willing to receive more events at the same time, anything to report? */
json_t *list = json_array();
json_error_t error;
if(event->payload) {
json_t *ev = json_loads(event->payload, 0, &error);
if(ev && json_is_object(ev)) /* FIXME Should we fail if this is not valid JSON? */
json_array_append_new(list, ev);
g_free(event->payload);
event->payload = NULL;
}
g_free(event);
event = NULL;
int events = 1;
while(events < max_events) {
event = g_async_queue_try_pop(session->messages);
if(event == NULL)
break;
if(event->payload) {
json_t *ev = json_loads(event->payload, 0, &error);
if(ev && json_is_object(ev)) /* FIXME Should we fail if this is not valid JSON? */
json_array_append_new(list, ev);
g_free(event->payload);
event->payload = NULL;
}
g_free(event);
event = NULL;
events++;
}
/* Return the array of messages and leave */
char *event_text = json_dumps(list, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
json_decref(list);
ret = janus_process_success(&source, event_text);
}
} else {
/* Still no message, wait */
ret = janus_ws_notifier(&source, max_events);
}
goto done;
}
/* Parse the JSON payload */
json_error_t error;
json_t *root = json_loads(payload, 0, &error);
if(!root) {
ret = janus_process_error(&source, 0, NULL, JANUS_ERROR_INVALID_JSON, "JSON error: on line %d: %s", error.line, error.text);
goto done;
}
if(!json_is_object(root)) {
ret = janus_process_error(&source, 0, NULL, JANUS_ERROR_INVALID_JSON_OBJECT, "JSON error: not an object");
json_decref(root);
goto done;
}
/* Check if we have session and handle identifiers */
guint64 session_id = session_path ? g_ascii_strtoll(session_path, NULL, 10) : 0;
guint64 handle_id = handle_path ? g_ascii_strtoll(handle_path, NULL, 10) : 0;
if(session_id > 0)
json_object_set_new(root, "session_id", json_integer(session_id));
if(handle_id > 0)
json_object_set_new(root, "handle_id", json_integer(handle_id));
ret = janus_process_incoming_request(&source, root);
done:
g_strfreev(basepath);
g_strfreev(path);
g_free(session_path);
g_free(handle_path);
return ret;
}
janus_request_source *janus_request_source_new(int type, void *source, void *msg) {
janus_request_source *req_source = (janus_request_source *)calloc(1, sizeof(janus_request_source));
req_source->type = type;
req_source->source = source;
req_source->msg = msg;
return req_source;
}
void janus_request_source_destroy(janus_request_source *req_source) {
if(req_source == NULL)
return;
req_source->source = NULL;
req_source->msg = NULL;
g_free(req_source);
}
int janus_process_incoming_request(janus_request_source *source, json_t *root) {
int ret = MHD_NO;
if(source == NULL || root == NULL) {
JANUS_LOG(LOG_ERR, "Missing source or payload to process, giving up...\n");
return ret;
}
/* 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 */
json_t *transaction = json_object_get(root, "transaction");
if(!transaction) {
ret = janus_process_error(source, session_id, NULL, JANUS_ERROR_MISSING_MANDATORY_ELEMENT, "Missing mandatory element (transaction)");
goto jsondone;
}
if(!json_is_string(transaction)) {
ret = janus_process_error(source, session_id, NULL, JANUS_ERROR_INVALID_ELEMENT_TYPE, "Invalid element type (transaction should be a string)");
goto jsondone;
}
const gchar *transaction_text = json_string_value(transaction);
json_t *message = json_object_get(root, "janus");
if(!message) {
ret = janus_process_error(source, session_id, transaction_text, JANUS_ERROR_MISSING_MANDATORY_ELEMENT, "Missing mandatory element (janus)");
goto jsondone;
}
if(!json_is_string(message)) {
ret = janus_process_error(source, session_id, transaction_text, JANUS_ERROR_INVALID_ELEMENT_TYPE, "Invalid element type (janus should be a string)");
goto jsondone;
}
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(source, 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));
char *reply_text = json_dumps(reply, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
json_decref(reply);
ret = janus_process_success(source, g_strdup(reply_text));
goto jsondone;
}
#ifdef HAVE_RABBITMQ
if(!strcasecmp(message_text, "rmqtest")) {
/* This is a request which is specifically conceived to send a notification
* on the RabbitMQ outgoing queue, and as such can help debugging potential
* issues there (e.g., whether Janus can still send messages on RabbitMQ) */
json_t *event = json_object();
json_object_set_new(event, "janus", json_string("rmqtest"));
char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
json_decref(event);
janus_rabbitmq_response *response = (janus_rabbitmq_response *)calloc(1, sizeof(janus_rabbitmq_response));
response->payload = event_text;
response->correlation_id = NULL;
g_async_queue_push(rmq_client->responses, response);
/* 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));
char *reply_text = json_dumps(reply, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
json_decref(reply);
ret = janus_process_success(source, g_strdup(reply_text));
goto jsondone;
}
#endif
if(strcasecmp(message_text, "create")) {
ret = janus_process_error(source, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
goto jsondone;
}
if(ws_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), ws_api_secret)) {
ret = janus_process_error(source, 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 */
if(!json_is_integer(id) || json_integer_value(id) < 0) {
ret = janus_process_error(source, session_id, transaction_text, JANUS_ERROR_INVALID_ELEMENT_TYPE, "Invalid element type (id should be a positive integer)");
goto jsondone;
}
session_id = json_integer_value(id);
if(session_id > 0 && janus_session_find(session_id) != NULL) {
/* Session ID already taken */
ret = janus_process_error(source, 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(source, session_id, transaction_text, JANUS_ERROR_UNKNOWN, "Memory error");
goto jsondone;
}
session_id = session->session_id;
/* Take note of the source that originated this session (HTTP, WebSockets, RabbitMQ?) */
session->source = janus_request_source_new(source->type, source->source, NULL);
#ifdef HAVE_WEBSOCKETS
if(source->type == JANUS_SOURCE_WEBSOCKETS) {
/* Add the new session to the list of sessions created by this WS client */
janus_websocket_client *client = (janus_websocket_client *)source->source;
if(client) {
janus_mutex_lock(&client->mutex);
if(client->sessions == NULL)
client->sessions = g_hash_table_new(NULL, NULL);
g_hash_table_insert(client->sessions, GUINT_TO_POINTER(session_id), session);
janus_mutex_unlock(&client->mutex);
}
}
#endif
#ifdef HAVE_RABBITMQ