-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
janus_http.c
2235 lines (2128 loc) · 87.2 KB
/
janus_http.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_http.c
* \author Lorenzo Miniero <[email protected]>
* \copyright GNU General Public License v3
* \brief Janus RESTs transport plugin
* \details This is an implementation of a RESTs transport for the
* Janus API, using the libmicrohttpd library (http://www.gnu.org/software/libmicrohttpd/).
* This module allows browsers to make use of HTTP to talk to the Janus core.
* Since a Janus instance may be deployed on a different domain than the web
* server hosting the web applications using it, the plugin automatically
* handles OPTIONS request to comply with the CORS specification.
* POST requests can be used to ask for the management of a session with
* the server, to attach to a plugin, to send messages to the plugin
* itself and so on. GET requests instead are used for getting events
* associated to a Janus session (and as such to all its plugin handles
* and the events plugins push in the session itself), using a long poll
* approach. A JavaScript library (janus.js) implements all of this on
* the client side automatically.
* \note There's a well known bug in libmicrohttpd that may cause it to
* spike to 100% of the CPU when using HTTPS on some distributions. In
* case you're interested in HTTPS support, it's better to just rely on
* HTTP in Janus, and put a frontend like Apache HTTPD or nginx to take
* care of securing the traffic. More details are available in \ref deploy.
*
* \ingroup transports
* \ref transports
*/
#include "transport.h"
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <microhttpd.h>
#ifdef HAVE_ENUM_MHD_RESULT
/* enum MHD_Result introduced in libmicrohttpd v0.9.71 */
typedef enum MHD_Result MHD_Result;
#else
typedef int MHD_Result;
#endif
#include "../debug.h"
#include "../apierror.h"
#include "../config.h"
#include "../mutex.h"
#include "../ip-utils.h"
#include "../utils.h"
/* Transport plugin information */
#define JANUS_HTTP_VERSION 2
#define JANUS_HTTP_VERSION_STRING "0.0.2"
#define JANUS_HTTP_DESCRIPTION "This transport plugin adds REST (HTTP/HTTPS) support to the Janus API via libmicrohttpd."
#define JANUS_HTTP_NAME "JANUS REST (HTTP/HTTPS) transport plugin"
#define JANUS_HTTP_AUTHOR "Meetecho s.r.l."
#define JANUS_HTTP_PACKAGE "janus.transport.http"
/* Transport methods */
janus_transport *create(void);
int janus_http_init(janus_transport_callbacks *callback, const char *config_path);
void janus_http_destroy(void);
int janus_http_get_api_compatibility(void);
int janus_http_get_version(void);
const char *janus_http_get_version_string(void);
const char *janus_http_get_description(void);
const char *janus_http_get_name(void);
const char *janus_http_get_author(void);
const char *janus_http_get_package(void);
gboolean janus_http_is_janus_api_enabled(void);
gboolean janus_http_is_admin_api_enabled(void);
int janus_http_send_message(janus_transport_session *transport, void *request_id, gboolean admin, json_t *message);
void janus_http_session_created(janus_transport_session *transport, guint64 session_id);
void janus_http_session_over(janus_transport_session *transport, guint64 session_id, gboolean timeout, gboolean claimed);
void janus_http_session_claimed(janus_transport_session *transport, guint64 session_id);
json_t *janus_http_query_transport(json_t *request);
/* Transport setup */
static janus_transport janus_http_transport =
JANUS_TRANSPORT_INIT (
.init = janus_http_init,
.destroy = janus_http_destroy,
.get_api_compatibility = janus_http_get_api_compatibility,
.get_version = janus_http_get_version,
.get_version_string = janus_http_get_version_string,
.get_description = janus_http_get_description,
.get_name = janus_http_get_name,
.get_author = janus_http_get_author,
.get_package = janus_http_get_package,
.is_janus_api_enabled = janus_http_is_janus_api_enabled,
.is_admin_api_enabled = janus_http_is_admin_api_enabled,
.send_message = janus_http_send_message,
.session_created = janus_http_session_created,
.session_over = janus_http_session_over,
.session_claimed = janus_http_session_claimed,
.query_transport = janus_http_query_transport,
);
/* Transport creator */
janus_transport *create(void) {
JANUS_LOG(LOG_VERB, "%s created!\n", JANUS_HTTP_NAME);
return &janus_http_transport;
}
/* MHD uses this value as default */
#define DEFAULT_CONNECTION_LIMIT (FD_SETSIZE-4)
static unsigned int connection_limit = DEFAULT_CONNECTION_LIMIT;
/* Useful stuff */
static gint initialized = 0, stopping = 0;
static janus_transport_callbacks *gateway = NULL;
static gboolean http_janus_api_enabled = FALSE;
static gboolean http_admin_api_enabled = FALSE;
static gboolean notify_events = TRUE;
static enum MHD_FLAG mhd_debug_flag = MHD_NO_FLAG;
/* JSON serialization options */
static size_t json_format = JSON_INDENT(3) | JSON_PRESERVE_ORDER;
/* Parameter validation (for tweaking and queries via Admin API) */
static struct janus_json_parameter request_parameters[] = {
{"request", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
};
static struct janus_json_parameter configure_parameters[] = {
{"events", JANUS_JSON_BOOL, 0},
{"json", JSON_STRING, 0},
};
/* Error codes (for the tweaking and queries via Admin API) */
#define JANUS_HTTP_ERROR_INVALID_REQUEST 411
#define JANUS_HTTP_ERROR_MISSING_ELEMENT 412
#define JANUS_HTTP_ERROR_INVALID_ELEMENT 413
#define JANUS_HTTP_ERROR_UNKNOWN_ERROR 499
/* Incoming HTTP message */
typedef struct janus_http_msg {
struct MHD_Connection *connection; /* The MHD connection this message came from */
volatile int suspended; /* Whether this connection is currently suspended */
volatile void *longpoll; /* Whether this is a long poll connection for a session */
int max_events; /* In case this is a long poll, how many events we should send back */
char *acro; /* Value of the Origin HTTP header, if any (needed for CORS) */
char *acrh; /* Value of the Access-Control-Request-Headers HTTP header, if any (needed for CORS) */
char *acrm; /* Value of the Access-Control-Request-Method HTTP header, if any (needed for CORS) */
char *contenttype; /* Content-Type of the payload */
char *payload; /* Payload of the message */
size_t len; /* Length of the message in octets */
gint64 session_id; /* Janus-Client session identifier this message belongs to */
char *response; /* The response from the core as a string */
size_t resplen; /* Length of the response in octets */
GSource *timeout; /* Timeout monitor, if any */
volatile gint timeout_flag; /* Whether a timeout hasn't fired yet */
volatile gint destroyed; /* Whether this session has been destroyed */
janus_refcount ref; /* Reference counter for this message */
} janus_http_msg;
static GHashTable *messages = NULL;
static janus_mutex messages_mutex = JANUS_MUTEX_INITIALIZER;
static void janus_http_msg_free(const janus_refcount *msg_ref) {
janus_http_msg *request = janus_refcount_containerof(msg_ref, janus_http_msg, ref);
/* This message can be destroyed, free all the resources */
if(!request)
return;
g_free(request->payload);
g_free(request->contenttype);
g_free(request->acro);
g_free(request->acrh);
g_free(request->acrm);
g_free(request->response);
g_free(request);
}
static void janus_http_msg_destroy(void *msg) {
janus_http_msg *request = (janus_http_msg *)msg;
if(request && g_atomic_int_compare_and_exchange(&request->destroyed, 0, 1))
janus_refcount_decrease(&request->ref);
}
/* Helper for long poll: HTTP events to push per session */
typedef struct janus_http_session {
guint64 session_id; /* Core session identifier */
GAsyncQueue *events; /* Events to notify for this session */
GList *longpolls; /* Long poll connection */
janus_mutex mutex; /* Mutex to lock this instance */
volatile gint destroyed; /* Whether this session has been destroyed */
janus_refcount ref; /* Reference counter for this session */
} janus_http_session;
/* We keep track of created sessions as we handle long polls */
static const char *keepalive_id = "keepalive";
static GHashTable *sessions = NULL;
static janus_mutex sessions_mutex = JANUS_MUTEX_INITIALIZER;
static void janus_http_session_destroy(janus_http_session *session) {
if(session && g_atomic_int_compare_and_exchange(&session->destroyed, 0, 1))
janus_refcount_decrease(&session->ref);
}
static void janus_http_session_free(const janus_refcount *session_ref) {
janus_http_session *session = janus_refcount_containerof(session_ref, janus_http_session, ref);
/* This session can be destroyed, free all the resources */
if(session->events) {
json_t *event = NULL;
while((event = g_async_queue_try_pop(session->events)) != NULL)
json_decref(event);
g_async_queue_unref(session->events);
}
g_free(session);
}
/* Custom GSource for tracking request timeouts (including long polls) */
typedef struct janus_http_request_timeout {
GSource source;
janus_transport_session *ts;
janus_http_session *session;
} janus_http_request_timeout;
/* Helper to handle timeouts */
static void janus_http_timeout(janus_transport_session *ts, janus_http_session *session);
/* GSource Functions */
static gboolean janus_http_request_timeout_dispatch(GSource *source, GSourceFunc callback, gpointer user_data) {
JANUS_LOG(LOG_DBG, "[%p] dispatch\n", source);
janus_http_request_timeout *t = (janus_http_request_timeout *)source;
/* Timeout fired, invoke the function */
janus_http_timeout(t->ts, t->session);
/* We're done */
g_source_destroy(source);
g_source_unref(source);
return G_SOURCE_REMOVE;
}
static void janus_http_request_timeout_finalize(GSource *source) {
JANUS_LOG(LOG_DBG, "[%p] finalize\n", source);
janus_http_request_timeout *timeout = (janus_http_request_timeout *)source;
if(timeout) {
if(timeout->session)
janus_refcount_decrease(&timeout->session->ref);
if(timeout->ts)
janus_refcount_decrease(&timeout->ts->ref);
}
}
static GSourceFuncs janus_http_request_timeout_funcs = {
NULL, NULL,
janus_http_request_timeout_dispatch,
janus_http_request_timeout_finalize,
NULL, NULL
};
static GSource *janus_http_request_timeout_create(janus_transport_session *ts, janus_http_session *session, gint timeout) {
GSource *source = g_source_new(&janus_http_request_timeout_funcs, sizeof(janus_http_request_timeout));
janus_http_request_timeout *t = (janus_http_request_timeout *)source;
t->ts = ts;
t->session = session;
g_source_set_ready_time(source, janus_get_monotonic_time() + timeout*G_USEC_PER_SEC);
JANUS_LOG(LOG_DBG, "[%p] create (%d)\n", source, timeout);
return source;
}
/* Callback (libmicrohttpd) invoked when a new connection is attempted on the REST API */
static MHD_Result janus_http_client_connect(void *cls, const struct sockaddr *addr, socklen_t addrlen);
/* Callback (libmicrohttpd) invoked when a new connection is attempted on the admin/monitor webserver */
static MHD_Result janus_http_admin_client_connect(void *cls, const struct sockaddr *addr, socklen_t addrlen);
/* Callback (libmicrohttpd) invoked when an HTTP message (GET, POST, OPTIONS, etc.) is available */
static MHD_Result janus_http_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);
/* Callback (libmicrohttpd) invoked when an admin/monitor HTTP message (GET, POST, OPTIONS, etc.) is available */
static MHD_Result janus_http_admin_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);
/* Callback (libmicrohttpd) invoked when headers of an incoming HTTP message have been parsed */
static MHD_Result janus_http_headers(void *cls, enum MHD_ValueKind kind, const char *key, const char *value);
/* Callback (libmicrohttpd) invoked when a request has been processed and can be freed */
static void janus_http_request_completed(void *cls, struct MHD_Connection *connection,
void **con_cls, enum MHD_RequestTerminationCode toe);
/* Callback to send data back after resuming a connection */
static ssize_t janus_http_response_callback(void *cls, uint64_t pos, char *buf, size_t max);
/* Worker to handle requests that are actually long polls */
static int janus_http_notifier(janus_http_msg *msg);
/* Helper to quickly send a success response */
static MHD_Result janus_http_return_success(janus_transport_session *ts, char *payload);
/* Helper to quickly send an error response */
static MHD_Result janus_http_return_error(janus_transport_session *ts, uint64_t session_id,
const char *transaction, gint error, const char *format, ...) G_GNUC_PRINTF(5, 6);
/* MHD Web Server */
static struct MHD_Daemon *ws = NULL, *sws = NULL;
static char *ws_path = NULL;
static char *cert_pem_bytes = NULL, *cert_key_bytes = NULL;
/* Admin/Monitor MHD Web Server */
static struct MHD_Daemon *admin_ws = NULL, *admin_sws = NULL;
static char *admin_ws_path = NULL;
/* Custom Access-Control-Allow-Origin value, if specified */
static char *allow_origin = NULL;
static gboolean enforce_cors = FALSE;
/* REST and Admin/Monitor ACL list */
static GList *janus_http_access_list = NULL, *janus_http_admin_access_list = NULL;
static janus_mutex access_list_mutex;
static void janus_http_allow_address(const char *ip, gboolean admin) {
if(ip == NULL)
return;
/* Is this an IP or an interface? */
janus_mutex_lock(&access_list_mutex);
if(!admin)
janus_http_access_list = g_list_append(janus_http_access_list, (gpointer)ip);
else
janus_http_admin_access_list = g_list_append(janus_http_admin_access_list, (gpointer)ip);
janus_mutex_unlock(&access_list_mutex);
}
static gboolean janus_http_is_allowed(const char *ip, gboolean admin) {
if(ip == NULL)
return FALSE;
if(!admin && janus_http_access_list == NULL)
return TRUE;
if(admin && janus_http_admin_access_list == NULL)
return TRUE;
janus_mutex_lock(&access_list_mutex);
GList *temp = admin ? janus_http_admin_access_list : janus_http_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;
}
/* Helper method to get the port from a struct sockaddr */
static uint16_t janus_http_sockaddr_to_port(struct sockaddr *address) {
if(address == NULL)
return 0;
struct sockaddr_in *sin = NULL;
struct sockaddr_in6 *sin6 = NULL;
switch(address->sa_family) {
case AF_INET:
sin = (struct sockaddr_in *)address;
return ntohs(sin->sin_port);
case AF_INET6:
sin6 = (struct sockaddr_in6 *)address;
return ntohs(sin6->sin6_port);
default:
/* Unknown family */
break;
}
return 0;
}
/* Random string helper (for transactions) */
static char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
static void janus_http_random_string(int length, char *buffer) {
if(length > 0 && buffer) {
int l = (int)(sizeof(charset)-1);
int i=0;
for(i=0; i<length; i++) {
int key = janus_random_uint32() % l;
buffer[i] = charset[key];
}
buffer[length-1] = '\0';
}
}
/* Event loop for timeout monitoring purposes */
static GThread *httptimer = NULL;
static GMainLoop *httploop = NULL;
static GMainContext *httpctx = NULL;
static gpointer janus_http_timer(gpointer user_data) {
JANUS_LOG(LOG_INFO, "HTTP transport timer started\n");
g_main_loop_run(httploop);
return NULL;
}
/* Helper to create a MHD daemon */
static struct MHD_Daemon *janus_http_create_daemon(gboolean admin, char *path,
const char *interface, const char *ip, int port,
const char *server_pem, const char *server_key, const char *password, const char *ciphers) {
struct MHD_Daemon *daemon = NULL;
gboolean secure = server_pem && server_key;
/* Any interface or IP address we need to limit ourselves to?
* NOTE WELL: specifying an interface does NOT bind to all IPs associated
* with that interface, but only to the first one that's detected */
static struct sockaddr_in addr = { 0 };
struct sockaddr_in6 addr6 = { 0 };
gboolean ipv6 = FALSE;
if(ip && strstr(ip, ":"))
ipv6 = TRUE;
gboolean found = FALSE;
if(ip) {
/* Do a quick check to see if we need to bind on all addresses of a specific family */
if(!strcasecmp(ip, "0.0.0.0")) {
/* Bind on all IPv4 addresses */
found = TRUE;
memset(&addr, 0, sizeof (struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
} else if(!strcasecmp(ip, "::")) {
/* Bind on all IPv6 addresses */
found = TRUE;
memset(&addr6, 0, sizeof (struct sockaddr_in6));
addr6.sin6_family = AF_INET6;
addr6.sin6_port = htons(port);
addr6.sin6_addr = in6addr_any;
}
}
if(!found && (ip || interface)) {
struct ifaddrs *ifaddr = NULL, *ifa = NULL;
int family = 0, s = 0, n = 0;
char host[NI_MAXHOST];
if(getifaddrs(&ifaddr) == -1) {
JANUS_LOG(LOG_ERR, "Error getting list of interfaces to bind %s API %s webserver...\n",
admin ? "Admin" : "Janus", secure ? "HTTPS" : "HTTP");
return NULL;
} else {
for(ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
if(ifa->ifa_addr == NULL)
continue;
family = ifa->ifa_addr->sa_family;
if(interface && strcasecmp(ifa->ifa_name, interface))
continue;
if(ifa->ifa_addr == NULL)
continue;
/* Skip interfaces which are not up and running */
if(!((ifa->ifa_flags & IFF_UP) && (ifa->ifa_flags & IFF_RUNNING)))
continue;
/* FIXME When being explicit about the interface only, we only bind IPv4 for now:
* specifying or adding a precise IPv6 address gets you an IPv6 binding instead */
if(!ipv6 && family == AF_INET) {
s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if(s != 0) {
JANUS_LOG(LOG_ERR, "Error doing a getnameinfo() to bind %s API %s webserver to '%s'...\n",
admin ? "Admin" : "Janus", secure ? "HTTPS" : "HTTP", ip ? ip : interface);
return NULL;
}
if(ip && strcmp(host, ip))
continue;
found = TRUE;
break;
} else if(ipv6 && family == AF_INET6) {
s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if(s != 0) {
JANUS_LOG(LOG_ERR, "Error doing a getnameinfo() to bind %s API %s webserver to '%s'...\n",
admin ? "Admin" : "Janus", secure ? "HTTPS" : "HTTP", ip ? ip : interface);
return NULL;
}
if(ip && strcmp(host, ip))
continue;
found = TRUE;
break;
}
}
freeifaddrs(ifaddr);
}
if(!found) {
JANUS_LOG(LOG_ERR, "Error binding to %s '%s' for %s API %s webserver...\n",
ip ? "IP" : "interface", ip ? ip : interface,
admin ? "Admin" : "Janus", secure ? "HTTPS" : "HTTP");
return NULL;
}
JANUS_LOG(LOG_VERB, "Going to bind the %s API %s webserver to %s (asked for %s)\n",
admin ? "Admin" : "Janus", secure ? "HTTPS" : "HTTP", host, ip ? ip : interface);
if(!ipv6) {
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
int res = inet_pton(AF_INET, host, &addr.sin_addr);
if(res != 1) {
JANUS_LOG(LOG_ERR, "Failed to convert address '%s' (%d)\n", host, res);
return NULL;
}
} else {
memset(&addr6, 0, sizeof(struct sockaddr_in6));
addr6.sin6_family = AF_INET6;
addr6.sin6_port = htons(port);
int res = inet_pton(AF_INET6, host, &addr6.sin6_addr);
if(res != 1) {
JANUS_LOG(LOG_ERR, "Failed to convert address '%s' (%d)\n", host, res);
return NULL;
}
}
}
if(!secure) {
/* HTTP web server */
if(!interface && !ip) {
/* Bind to all interfaces */
JANUS_LOG(LOG_VERB, "Binding to all interfaces for the %s API %s webserver\n",
admin ? "Admin" : "Janus", secure ? "HTTPS" : "HTTP");
daemon = MHD_start_daemon(
MHD_USE_AUTO_INTERNAL_THREAD | MHD_USE_AUTO | MHD_USE_SUSPEND_RESUME | MHD_USE_DUAL_STACK | mhd_debug_flag,
port,
admin ? &janus_http_admin_client_connect : &janus_http_client_connect,
NULL,
admin ? &janus_http_admin_handler : &janus_http_handler,
path,
MHD_OPTION_NOTIFY_COMPLETED, &janus_http_request_completed, NULL,
MHD_OPTION_CONNECTION_TIMEOUT, 120,
MHD_OPTION_CONNECTION_LIMIT, connection_limit,
MHD_OPTION_END);
} else {
/* Bind to the interface that was specified */
JANUS_LOG(LOG_VERB, "Binding to %s '%s' for the %s API %s webserver\n",
ip ? "IP" : "interface", ip ? ip : interface,
admin ? "Admin" : "Janus", secure ? "HTTPS" : "HTTP");
daemon = MHD_start_daemon(
MHD_USE_AUTO_INTERNAL_THREAD | MHD_USE_AUTO | MHD_USE_SUSPEND_RESUME | (ipv6 ? MHD_USE_IPv6 : 0) | mhd_debug_flag,
port,
admin ? &janus_http_admin_client_connect : &janus_http_client_connect,
NULL,
admin ? &janus_http_admin_handler : &janus_http_handler,
path,
MHD_OPTION_NOTIFY_COMPLETED, &janus_http_request_completed, NULL,
MHD_OPTION_SOCK_ADDR, ipv6 ? (struct sockaddr *)&addr6 : (struct sockaddr *)&addr,
MHD_OPTION_CONNECTION_TIMEOUT, 120,
MHD_OPTION_CONNECTION_LIMIT, connection_limit,
MHD_OPTION_END);
}
} else {
/* HTTPS web server, read certificate and key */
g_file_get_contents(server_pem, &cert_pem_bytes, NULL, NULL);
g_file_get_contents(server_key, &cert_key_bytes, NULL, NULL);
/* Start webserver */
if(!interface && !ip) {
/* Bind to all interfaces */
JANUS_LOG(LOG_VERB, "Binding to all interfaces for the %s API %s webserver\n",
admin ? "Admin" : "Janus", secure ? "HTTPS" : "HTTP");
daemon = MHD_start_daemon(
MHD_USE_SSL | MHD_USE_AUTO_INTERNAL_THREAD | MHD_USE_AUTO | MHD_USE_SUSPEND_RESUME | MHD_USE_DUAL_STACK | mhd_debug_flag,
port,
admin ? &janus_http_admin_client_connect : &janus_http_client_connect,
NULL,
admin ? &janus_http_admin_handler : &janus_http_handler,
path,
MHD_OPTION_NOTIFY_COMPLETED, &janus_http_request_completed, NULL,
MHD_OPTION_HTTPS_PRIORITIES, ciphers,
MHD_OPTION_HTTPS_MEM_CERT, cert_pem_bytes,
MHD_OPTION_HTTPS_MEM_KEY, cert_key_bytes,
MHD_OPTION_HTTPS_KEY_PASSWORD, password,
MHD_OPTION_CONNECTION_TIMEOUT, 120,
MHD_OPTION_CONNECTION_LIMIT, connection_limit,
MHD_OPTION_END);
} else {
/* Bind to the interface that was specified */
JANUS_LOG(LOG_VERB, "Binding to %s '%s' for the %s API %s webserver\n",
ip ? "IP" : "interface", ip ? ip : interface,
admin ? "Admin" : "Janus", secure ? "HTTPS" : "HTTP");
daemon = MHD_start_daemon(
MHD_USE_SSL | MHD_USE_AUTO_INTERNAL_THREAD | MHD_USE_AUTO | MHD_USE_SUSPEND_RESUME | (ipv6 ? MHD_USE_IPv6 : 0) | mhd_debug_flag,
port,
admin ? &janus_http_admin_client_connect : &janus_http_client_connect,
NULL,
admin ? &janus_http_admin_handler : &janus_http_handler,
path,
MHD_OPTION_NOTIFY_COMPLETED, &janus_http_request_completed, NULL,
MHD_OPTION_HTTPS_PRIORITIES, ciphers,
MHD_OPTION_HTTPS_MEM_CERT, cert_pem_bytes,
MHD_OPTION_HTTPS_MEM_KEY, cert_key_bytes,
MHD_OPTION_HTTPS_KEY_PASSWORD, password,
MHD_OPTION_SOCK_ADDR, ipv6 ? (struct sockaddr *)&addr6 : (struct sockaddr *)&addr,
MHD_OPTION_CONNECTION_TIMEOUT, 120,
MHD_OPTION_CONNECTION_LIMIT, connection_limit,
MHD_OPTION_END);
}
}
return daemon;
}
/* Static helper method to fill in the CORS headers */
static void janus_http_add_cors_headers(janus_http_msg *msg, struct MHD_Response *response) {
if(msg == NULL || g_atomic_int_get(&msg->destroyed) || response == NULL)
return;
janus_refcount_increase(&msg->ref);
MHD_add_response_header(response, "Access-Control-Allow-Origin", allow_origin ? allow_origin : "*");
if(allow_origin) {
/* We need these two headers as well, in case Access-Control-Allow-Origin is custom */
MHD_add_response_header(response, "Access-Control-Allow-Credentials", "true");
MHD_add_response_header(response, "Vary", "Origin");
}
MHD_add_response_header(response, "Access-Control-Max-Age", "86400");
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);
janus_refcount_decrease(&msg->ref);
}
/* Static callback that we register to */
static void janus_http_mhd_panic(void *cls, const char *file, unsigned int line, const char *reason) {
JANUS_LOG(LOG_WARN, "[%s]: Error in GNU libmicrohttpd %s:%u: %s\n",
JANUS_HTTP_PACKAGE, file, line, reason);
}
/* Transport implementation */
int janus_http_init(janus_transport_callbacks *callback, const char *config_path) {
if(g_atomic_int_get(&stopping)) {
/* Still stopping from before */
return -1;
}
if(callback == NULL || config_path == NULL) {
/* Invalid arguments */
return -1;
}
/* This is the callback we'll need to invoke to contact the Janus core */
gateway = callback;
/* Register a function to detect problems for which MHD would typically abort */
MHD_set_panic_func(&janus_http_mhd_panic, NULL);
/* Start the timer */
httpctx = g_main_context_new();
httploop = g_main_loop_new(httpctx, FALSE);
GError *error = NULL;
httptimer = g_thread_try_new("http timer", &janus_http_timer, NULL, &error);
if(error != NULL) {
JANUS_LOG(LOG_FATAL, "Got error %d (%s) trying to start HTTP timer...\n",
error->code, error->message ? error->message : "??");
g_error_free(error);
return -1;
}
/* Read configuration */
char filename[255];
g_snprintf(filename, 255, "%s/%s.jcfg", config_path, JANUS_HTTP_PACKAGE);
JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
janus_config *config = janus_config_parse(filename);
if(config == NULL) {
JANUS_LOG(LOG_WARN, "Couldn't find .jcfg configuration file (%s), trying .cfg\n", JANUS_HTTP_PACKAGE);
g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_HTTP_PACKAGE);
JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
config = janus_config_parse(filename);
}
if(config != NULL) {
janus_config_print(config);
janus_config_category *config_general = janus_config_get_create(config, NULL, janus_config_type_category, "general");
janus_config_category *config_admin = janus_config_get_create(config, NULL, janus_config_type_category, "admin");
janus_config_category *config_cors = janus_config_get_create(config, NULL, janus_config_type_category, "cors");
janus_config_category *config_certs = janus_config_get_create(config, NULL, janus_config_type_category, "certificates");
/* Handle configuration */
janus_config_item *item = janus_config_get(config, config_general, janus_config_type_item, "json");
if(item && item->value) {
/* Check how we need to format/serialize the JSON output */
if(!strcasecmp(item->value, "indented")) {
/* Default: indented, we use three spaces for that */
json_format = JSON_INDENT(3) | JSON_PRESERVE_ORDER;
} else if(!strcasecmp(item->value, "plain")) {
/* Not indented and no new lines, but still readable */
json_format = JSON_INDENT(0) | JSON_PRESERVE_ORDER;
} else if(!strcasecmp(item->value, "compact")) {
/* Compact, so no spaces between separators */
json_format = JSON_COMPACT | JSON_PRESERVE_ORDER;
} else {
JANUS_LOG(LOG_WARN, "Unsupported JSON format option '%s', using default (indented)\n", item->value);
json_format = JSON_INDENT(3) | JSON_PRESERVE_ORDER;
}
}
/* Check if we need to send events to handlers */
janus_config_item *events = janus_config_get(config, config_general, janus_config_type_item, "events");
if(events != NULL && events->value != NULL)
notify_events = janus_is_true(events->value);
if(!notify_events && callback->events_is_enabled()) {
JANUS_LOG(LOG_WARN, "Notification of events to handlers disabled for %s\n", JANUS_HTTP_NAME);
}
/* Check the base paths */
item = janus_config_get(config, config_general, janus_config_type_item, "base_path");
if(item && item->value) {
if(item->value[0] != '/') {
JANUS_LOG(LOG_FATAL, "Invalid base path %s (it should start with a /, e.g., /janus\n", item->value);
return -1;
}
ws_path = g_strdup(item->value);
if(strlen(ws_path) > 1 && ws_path[strlen(ws_path)-1] == '/') {
/* Remove the trailing slash, it makes things harder when we parse requests later */
ws_path[strlen(ws_path)-1] = '\0';
}
} else {
ws_path = g_strdup("/janus");
}
/* Do the same for the admin/monitor interface */
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_base_path");
if(item && item->value) {
if(item->value[0] != '/') {
JANUS_LOG(LOG_FATAL, "Invalid admin/monitor base path %s (it should start with a /, e.g., /admin\n", item->value);
return -1;
}
admin_ws_path = g_strdup(item->value);
if(strlen(admin_ws_path) > 1 && admin_ws_path[strlen(admin_ws_path)-1] == '/') {
/* Remove the trailing slash, it makes things harder when we parse requests later */
admin_ws_path[strlen(admin_ws_path)-1] = '\0';
}
} else {
admin_ws_path = g_strdup("/admin");
}
/* Check the open connections limit for mhd */
item = janus_config_get(config, config_general, janus_config_type_item, "mhd_connection_limit");
if(item && item->value && janus_string_to_uint32(item->value, &connection_limit) < 0) {
JANUS_LOG(LOG_ERR, "Invalid mhd_connection_limit (%s), falling back to default\n", item->value);
connection_limit = DEFAULT_CONNECTION_LIMIT;
}
/* Should we set the debug flag in libmicrohttpd? */
item = janus_config_get(config, config_general, janus_config_type_item, "mhd_debug");
if(item && item->value && janus_is_true(item->value))
mhd_debug_flag = MHD_USE_DEBUG;
/* Any ACL for either the Janus or Admin API? */
item = janus_config_get(config, config_general, janus_config_type_item, "acl");
if(item && item->value) {
char **list = g_strsplit(item->value, ",", -1);
char *index = list[0];
if(index != NULL) {
int i=0;
while(index != NULL) {
if(strlen(index) > 0) {
JANUS_LOG(LOG_INFO, "Adding '%s' to the Janus API allowed list...\n", index);
janus_http_allow_address(g_strdup(index), FALSE);
}
i++;
index = list[i];
}
}
g_strfreev(list);
list = NULL;
}
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_acl");
if(item && item->value) {
char **list = g_strsplit(item->value, ",", -1);
char *index = list[0];
if(index != NULL) {
int i=0;
while(index != NULL) {
if(strlen(index) > 0) {
JANUS_LOG(LOG_INFO, "Adding '%s' to the Admin/monitor allowed list...\n", index);
janus_http_allow_address(g_strdup(index), TRUE);
}
i++;
index = list[i];
}
}
g_strfreev(list);
list = NULL;
}
/* Any custom value for the Access-Control-Allow-Origin header? */
item = janus_config_get(config, config_cors, janus_config_type_item, "allow_origin");
if(item && item->value) {
allow_origin = g_strdup(item->value);
JANUS_LOG(LOG_INFO, "Restricting Access-Control-Allow-Origin to '%s'\n", allow_origin);
}
if(allow_origin != NULL) {
item = janus_config_get(config, config_cors, janus_config_type_item, "enforce_cors");
if(item && item->value && janus_is_true(item->value)) {
enforce_cors = TRUE;
JANUS_LOG(LOG_INFO, "Going to enforce CORS by 403 errors\n");
}
}
/* Start with the Janus API web server now */
item = janus_config_get(config, config_general, janus_config_type_item, "http");
if(!item || !item->value || !janus_is_true(item->value)) {
JANUS_LOG(LOG_VERB, "HTTP webserver disabled\n");
} else {
uint16_t wsport = 8088;
item = janus_config_get(config, config_general, janus_config_type_item, "port");
if(item && item->value && janus_string_to_uint16(item->value, &wsport) < 0) {
JANUS_LOG(LOG_ERR, "Invalid port (%s), falling back to default\n", item->value);
wsport = 8088;
}
const char *interface = NULL;
item = janus_config_get(config, config_general, janus_config_type_item, "interface");
if(item && item->value)
interface = item->value;
const char *ip = NULL;
item = janus_config_get(config, config_general, janus_config_type_item, "ip");
if(item && item->value)
ip = item->value;
ws = janus_http_create_daemon(FALSE, ws_path, interface, ip, wsport,
NULL, NULL, NULL, NULL);
if(ws == NULL) {
JANUS_LOG(LOG_FATAL, "Couldn't start webserver on port %d...\n", wsport);
} else {
JANUS_LOG(LOG_INFO, "HTTP webserver started (port %d, %s path listener)...\n", wsport, ws_path);
}
}
/* Do we also have to provide an HTTPS one? */
char *server_pem = NULL;
item = janus_config_get(config, config_certs, janus_config_type_item, "cert_pem");
if(item && item->value)
server_pem = (char *)item->value;
char *server_key = NULL;
item = janus_config_get(config, config_certs, janus_config_type_item, "cert_key");
if(item && item->value)
server_key = (char *)item->value;
char *password = NULL;
item = janus_config_get(config, config_certs, janus_config_type_item, "cert_pwd");
if(item && item->value)
password = (char *)item->value;
const char *ciphers = "NORMAL";
item = janus_config_get(config, config_certs, janus_config_type_item, "ciphers");
if(item && item->value)
ciphers = item->value;
if(server_key)
JANUS_LOG(LOG_VERB, "Using certificates:\n\t%s\n\t%s\n", server_pem, server_key);
item = janus_config_get(config, config_general, janus_config_type_item, "https");
if(!item || !item->value || !janus_is_true(item->value)) {
JANUS_LOG(LOG_VERB, "HTTPS webserver disabled\n");
} else {
if(!server_key || !server_pem) {
JANUS_LOG(LOG_FATAL, "Missing certificate/key path\n");
} else {
uint16_t swsport = 8089;
item = janus_config_get(config, config_general, janus_config_type_item, "secure_port");
if(item && item->value && janus_string_to_uint16(item->value, &swsport) < 0) {
JANUS_LOG(LOG_ERR, "Invalid port (%s), falling back to default\n", item->value);
swsport = 8089;
}
const char *interface = NULL;
item = janus_config_get(config, config_general, janus_config_type_item, "secure_interface");
if(item && item->value)
interface = item->value;
const char *ip = NULL;
item = janus_config_get(config, config_general, janus_config_type_item, "secure_ip");
if(item && item->value)
ip = item->value;
sws = janus_http_create_daemon(FALSE, ws_path, interface, ip, swsport,
server_pem, server_key, password, ciphers);
if(sws == NULL) {
JANUS_LOG(LOG_FATAL, "Couldn't start secure webserver on port %d...\n", swsport);
} else {
JANUS_LOG(LOG_INFO, "HTTPS webserver started (port %d, %s path listener)...\n", swsport, ws_path);
}
}
}
/* Admin/monitor time: start web server, if enabled */
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_http");
if(!item || !item->value || !janus_is_true(item->value)) {
JANUS_LOG(LOG_VERB, "Admin/monitor HTTP webserver disabled\n");
} else {
uint16_t wsport = 7088;
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_port");
if(item && item->value && janus_string_to_uint16(item->value, &wsport) < 0) {
JANUS_LOG(LOG_ERR, "Invalid port (%s), falling back to default\n", item->value);
wsport = 7088;
}
const char *interface = NULL;
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_interface");
if(item && item->value)
interface = item->value;
const char *ip = NULL;
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_ip");
if(item && item->value)
ip = item->value;
admin_ws = janus_http_create_daemon(TRUE, admin_ws_path, interface, ip, wsport,
NULL, NULL, NULL, NULL);
if(admin_ws == NULL) {
JANUS_LOG(LOG_FATAL, "Couldn't start admin/monitor webserver on port %d...\n", wsport);
} else {
JANUS_LOG(LOG_INFO, "Admin/monitor HTTP webserver started (port %d, %s path listener)...\n", wsport, admin_ws_path);
}
}
/* Do we also have to provide an HTTPS one? */
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_https");
if(!item || !item->value || !janus_is_true(item->value)) {
JANUS_LOG(LOG_VERB, "Admin/monitor HTTPS webserver disabled\n");
} else {
if(!server_key) {
JANUS_LOG(LOG_FATAL, "Missing certificate/key path\n");
} else {
uint16_t swsport = 7889;
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_secure_port");
if(item && item->value && janus_string_to_uint16(item->value, &swsport) < 0) {
JANUS_LOG(LOG_ERR, "Invalid port (%s), falling back to default\n", item->value);
swsport = 7889;
}
const char *interface = NULL;
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_secure_interface");
if(item && item->value)
interface = item->value;
const char *ip = NULL;
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_secure_ip");
if(item && item->value)
ip = item->value;
admin_sws = janus_http_create_daemon(TRUE, admin_ws_path, interface, ip, swsport,
server_pem, server_key, password, ciphers);
if(admin_sws == NULL) {
JANUS_LOG(LOG_FATAL, "Couldn't start secure admin/monitor webserver on port %d...\n", swsport);
} else {
JANUS_LOG(LOG_INFO, "Admin/monitor HTTPS webserver started (port %d, %s path listener)...\n",
swsport, admin_ws_path);
}
}
}
}
janus_config_destroy(config);
config = NULL;
if(!ws && !sws && !admin_ws && !admin_sws) {
JANUS_LOG(LOG_WARN, "No HTTP/HTTPS server started, giving up...\n");
return -1; /* No point in keeping the plugin loaded */
}
http_janus_api_enabled = ws || sws;
http_admin_api_enabled = admin_ws || admin_sws;
messages = g_hash_table_new_full(NULL, NULL, NULL, (GDestroyNotify)janus_transport_session_destroy);
sessions = g_hash_table_new_full(g_int64_hash, g_int64_equal, (GDestroyNotify)g_free, (GDestroyNotify)janus_http_session_destroy);
/* Done */
g_atomic_int_set(&initialized, 1);
JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_HTTP_NAME);
return 0;
}
void janus_http_destroy(void) {
if(!g_atomic_int_get(&initialized))
return;
g_atomic_int_set(&stopping, 1);
g_main_loop_quit(httploop);
g_thread_join(httptimer);
g_main_context_unref(httpctx);
/* Resume all pending connections, before stopping the webservers */
janus_mutex_lock(&messages_mutex);
GHashTableIter iter;
gpointer value;
g_hash_table_iter_init(&iter, messages);
while(g_hash_table_iter_next(&iter, NULL, &value)) {
janus_transport_session *transport = value;
janus_http_msg *msg = (janus_http_msg *)transport->transport_p;
if(msg != NULL && !g_atomic_int_get(&msg->destroyed)) {
MHD_resume_connection(msg->connection);
}
}
janus_mutex_unlock(&messages_mutex);
JANUS_LOG(LOG_INFO, "Stopping webserver(s)...\n");
if(ws)
MHD_stop_daemon(ws);
ws = NULL;
if(sws)
MHD_stop_daemon(sws);
sws = NULL;
if(admin_ws)
MHD_stop_daemon(admin_ws);
admin_ws = NULL;
if(admin_sws)
MHD_stop_daemon(admin_sws);
admin_sws = NULL;
g_free((gpointer)cert_pem_bytes);
cert_pem_bytes = NULL;
g_free((gpointer)cert_key_bytes);
cert_key_bytes = NULL;
g_free(allow_origin);
allow_origin = NULL;
janus_mutex_lock(&messages_mutex);
g_hash_table_destroy(messages);
messages = NULL;
janus_mutex_unlock(&messages_mutex);
janus_mutex_lock(&sessions_mutex);
g_hash_table_destroy(sessions);
sessions = NULL;
janus_mutex_unlock(&sessions_mutex);
g_atomic_int_set(&initialized, 0);
g_atomic_int_set(&stopping, 0);
JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_HTTP_NAME);
}
int janus_http_get_api_compatibility(void) {
/* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
return JANUS_TRANSPORT_API_VERSION;
}
int janus_http_get_version(void) {
return JANUS_HTTP_VERSION;
}
const char *janus_http_get_version_string(void) {
return JANUS_HTTP_VERSION_STRING;
}
const char *janus_http_get_description(void) {
return JANUS_HTTP_DESCRIPTION;
}