forked from meetecho/janus-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjanus_websockets.c
1568 lines (1481 loc) · 59.5 KB
/
janus_websockets.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_websockets.c
* \author Lorenzo Miniero <[email protected]>
* \copyright GNU General Public License v3
* \brief Janus WebSockets transport plugin
* \details This is an implementation of a WebSockets transport for the
* Janus API, using the libwebsockets library (http://libwebsockets.org).
* This means that, with the help of this module, browsers or applications
* (e.g., nodejs server side implementations) can also make use of
* WebSockets to make requests to Janus. In that case, the same
* WebSocket can be used for both sending requests and receiving
* notifications, without the need for long polls. At the same time,
* without the concept of a REST path, requests sent through the
* WebSockets interface will need to include, when needed, additional
* pieces of information like \c session_id and \c handle_id. That is,
* where you'd send a Janus request related to a specific session to the
* \c /janus/\<session> path, with WebSockets you'd have to send the same
* request with an additional \c session_id field in the JSON payload.
* The same applies for the handle. The JavaScript library (janus.js)
* implements all of this on the client side automatically.
* \note When you create a session using WebSockets, a subscription to
* the events related to it is done automatically, so no need for an
* explicit request as the GET in the plain HTTP API. Closing a WebSocket
* will also destroy all the sessions it created.
*
* \ingroup transports
* \ref transports
*/
#include "transport.h"
#include <arpa/inet.h>
#include <net/if.h>
#include <ifaddrs.h>
#include <libwebsockets.h>
#include "../debug.h"
#include "../apierror.h"
#include "../config.h"
#include "../mutex.h"
#include "../utils.h"
/* Transport plugin information */
#define JANUS_WEBSOCKETS_VERSION 1
#define JANUS_WEBSOCKETS_VERSION_STRING "0.0.1"
#define JANUS_WEBSOCKETS_DESCRIPTION "This transport plugin adds WebSockets support to the Janus API via libwebsockets."
#define JANUS_WEBSOCKETS_NAME "JANUS WebSockets transport plugin"
#define JANUS_WEBSOCKETS_AUTHOR "Meetecho s.r.l."
#define JANUS_WEBSOCKETS_PACKAGE "janus.transport.websockets"
/* Transport methods */
janus_transport *create(void);
int janus_websockets_init(janus_transport_callbacks *callback, const char *config_path);
void janus_websockets_destroy(void);
int janus_websockets_get_api_compatibility(void);
int janus_websockets_get_version(void);
const char *janus_websockets_get_version_string(void);
const char *janus_websockets_get_description(void);
const char *janus_websockets_get_name(void);
const char *janus_websockets_get_author(void);
const char *janus_websockets_get_package(void);
gboolean janus_websockets_is_janus_api_enabled(void);
gboolean janus_websockets_is_admin_api_enabled(void);
int janus_websockets_send_message(janus_transport_session *transport, void *request_id, gboolean admin, json_t *message);
void janus_websockets_session_created(janus_transport_session *transport, guint64 session_id);
void janus_websockets_session_over(janus_transport_session *transport, guint64 session_id, gboolean timeout, gboolean claimed);
void janus_websockets_session_claimed(janus_transport_session *transport, guint64 session_id);
json_t *janus_websockets_query_transport(json_t *request);
/* Transport setup */
static janus_transport janus_websockets_transport =
JANUS_TRANSPORT_INIT (
.init = janus_websockets_init,
.destroy = janus_websockets_destroy,
.get_api_compatibility = janus_websockets_get_api_compatibility,
.get_version = janus_websockets_get_version,
.get_version_string = janus_websockets_get_version_string,
.get_description = janus_websockets_get_description,
.get_name = janus_websockets_get_name,
.get_author = janus_websockets_get_author,
.get_package = janus_websockets_get_package,
.is_janus_api_enabled = janus_websockets_is_janus_api_enabled,
.is_admin_api_enabled = janus_websockets_is_admin_api_enabled,
.send_message = janus_websockets_send_message,
.session_created = janus_websockets_session_created,
.session_over = janus_websockets_session_over,
.session_claimed = janus_websockets_session_claimed,
.query_transport = janus_websockets_query_transport,
);
/* Transport creator */
janus_transport *create(void) {
JANUS_LOG(LOG_VERB, "%s created!\n", JANUS_WEBSOCKETS_NAME);
return &janus_websockets_transport;
}
/* Useful stuff */
static gint initialized = 0, stopping = 0;
static janus_transport_callbacks *gateway = NULL;
static gboolean ws_janus_api_enabled = FALSE;
static gboolean ws_admin_api_enabled = FALSE;
static gboolean notify_events = TRUE;
/* Clients maps */
#if (LWS_LIBRARY_VERSION_MAJOR >= 3)
static GHashTable *clients = NULL, *writable_clients = NULL;
#endif
static janus_mutex writable_mutex;
/* 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},
{"logging", JSON_STRING, 0},
};
/* Error codes (for the tweaking and queries via Admin API) */
#define JANUS_WEBSOCKETS_ERROR_INVALID_REQUEST 411
#define JANUS_WEBSOCKETS_ERROR_MISSING_ELEMENT 412
#define JANUS_WEBSOCKETS_ERROR_INVALID_ELEMENT 413
#define JANUS_WEBSOCKETS_ERROR_UNKNOWN_ERROR 499
/* Logging */
static int ws_log_level = 0;
static const char *janus_websockets_get_level_str(int level) {
switch(level) {
case LLL_ERR:
return "ERR";
case LLL_WARN:
return "WARN";
case LLL_NOTICE:
return "NOTICE";
case LLL_INFO:
return "INFO";
case LLL_DEBUG:
return "DEBUG";
case LLL_PARSER:
return "PARSER";
case LLL_HEADER:
return "HEADER";
case LLL_EXT:
return "EXT";
case LLL_CLIENT:
return "CLIENT";
case LLL_LATENCY:
return "LATENCY";
#if (LWS_LIBRARY_VERSION_MAJOR >= 2 && LWS_LIBRARY_VERSION_MINOR >= 2) || (LWS_LIBRARY_VERSION_MAJOR >= 3)
case LLL_USER:
return "USER";
#endif
case LLL_COUNT:
return "COUNT";
default:
return NULL;
}
}
static void janus_websockets_log_emit_function(int level, const char *line) {
/* FIXME Do we want to use different Janus debug levels according to the level here? */
JANUS_LOG(LOG_INFO, "[libwebsockets][%s] %s", janus_websockets_get_level_str(level), line);
}
/* WebSockets service thread */
static GThread *ws_thread = NULL;
void *janus_websockets_thread(void *data);
/* WebSocket client session */
typedef struct janus_websockets_client {
struct lws *wsi; /* The libwebsockets client instance */
GAsyncQueue *messages; /* Queue of outgoing messages to push */
char *incoming; /* Buffer containing the incoming message to process (in case there are fragments) */
unsigned char *buffer; /* Buffer containing the message to send */
size_t buflen; /* Length of the buffer (may be resized after re-allocations) */
size_t bufpending; /* Data an interrupted previous write couldn't send */
size_t bufoffset; /* Offset from where the interrupted previous write should resume */
volatile gint destroyed; /* Whether this libwebsockets client instance has been closed */
janus_transport_session *ts; /* Janus core-transport session */
} janus_websockets_client;
/* libwebsockets WS context */
static struct lws_context *wsc = NULL;
/* Callbacks for HTTP-related events (automatically rejected) */
static int janus_websockets_callback_http(
struct lws *wsi,
enum lws_callback_reasons reason,
void *user, void *in, size_t len);
static int janus_websockets_callback_https(
struct lws *wsi,
enum lws_callback_reasons reason,
void *user, void *in, size_t len);
/* Callbacks for WebSockets-related events */
static int janus_websockets_callback(
struct lws *wsi,
enum lws_callback_reasons reason,
void *user, void *in, size_t len);
static int janus_websockets_callback_secure(
struct lws *wsi,
enum lws_callback_reasons reason,
void *user, void *in, size_t len);
static int janus_websockets_admin_callback(
struct lws *wsi,
enum lws_callback_reasons reason,
void *user, void *in, size_t len);
static int janus_websockets_admin_callback_secure(
struct lws *wsi,
enum lws_callback_reasons reason,
void *user, void *in, size_t len);
/* Protocol mappings */
static struct lws_protocols ws_protocols[] = {
{ "http-only", janus_websockets_callback_http, 0, 0 },
{ "janus-protocol", janus_websockets_callback, sizeof(janus_websockets_client), 0 },
{ NULL, NULL, 0 }
};
static struct lws_protocols sws_protocols[] = {
{ "http-only", janus_websockets_callback_https, 0, 0 },
{ "janus-protocol", janus_websockets_callback_secure, sizeof(janus_websockets_client), 0 },
{ NULL, NULL, 0 }
};
static struct lws_protocols admin_ws_protocols[] = {
{ "http-only", janus_websockets_callback_http, 0, 0 },
{ "janus-admin-protocol", janus_websockets_admin_callback, sizeof(janus_websockets_client), 0 },
{ NULL, NULL, 0 }
};
static struct lws_protocols admin_sws_protocols[] = {
{ "http-only", janus_websockets_callback_https, 0, 0 },
{ "janus-admin-protocol", janus_websockets_admin_callback_secure, sizeof(janus_websockets_client), 0 },
{ NULL, NULL, 0 }
};
/* Helper for debugging reasons */
#define CASE_STR(name) case name: return #name
static const char *janus_websockets_reason_string(enum lws_callback_reasons reason) {
switch(reason) {
CASE_STR(LWS_CALLBACK_ESTABLISHED);
CASE_STR(LWS_CALLBACK_CLIENT_CONNECTION_ERROR);
CASE_STR(LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH);
CASE_STR(LWS_CALLBACK_CLIENT_ESTABLISHED);
CASE_STR(LWS_CALLBACK_CLOSED);
CASE_STR(LWS_CALLBACK_CLOSED_HTTP);
CASE_STR(LWS_CALLBACK_RECEIVE);
CASE_STR(LWS_CALLBACK_CLIENT_RECEIVE);
CASE_STR(LWS_CALLBACK_CLIENT_RECEIVE_PONG);
CASE_STR(LWS_CALLBACK_CLIENT_WRITEABLE);
CASE_STR(LWS_CALLBACK_SERVER_WRITEABLE);
CASE_STR(LWS_CALLBACK_HTTP);
CASE_STR(LWS_CALLBACK_HTTP_BODY);
CASE_STR(LWS_CALLBACK_HTTP_BODY_COMPLETION);
CASE_STR(LWS_CALLBACK_HTTP_FILE_COMPLETION);
CASE_STR(LWS_CALLBACK_HTTP_WRITEABLE);
CASE_STR(LWS_CALLBACK_ADD_HEADERS);
CASE_STR(LWS_CALLBACK_FILTER_NETWORK_CONNECTION);
CASE_STR(LWS_CALLBACK_FILTER_HTTP_CONNECTION);
CASE_STR(LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED);
CASE_STR(LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION);
CASE_STR(LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS);
CASE_STR(LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS);
CASE_STR(LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION);
CASE_STR(LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER);
CASE_STR(LWS_CALLBACK_CONFIRM_EXTENSION_OKAY);
CASE_STR(LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED);
CASE_STR(LWS_CALLBACK_PROTOCOL_INIT);
CASE_STR(LWS_CALLBACK_PROTOCOL_DESTROY);
CASE_STR(LWS_CALLBACK_WSI_CREATE);
CASE_STR(LWS_CALLBACK_WSI_DESTROY);
CASE_STR(LWS_CALLBACK_GET_THREAD_ID);
CASE_STR(LWS_CALLBACK_ADD_POLL_FD);
CASE_STR(LWS_CALLBACK_DEL_POLL_FD);
CASE_STR(LWS_CALLBACK_CHANGE_MODE_POLL_FD);
CASE_STR(LWS_CALLBACK_LOCK_POLL);
CASE_STR(LWS_CALLBACK_UNLOCK_POLL);
CASE_STR(LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY);
CASE_STR(LWS_CALLBACK_USER);
CASE_STR(LWS_CALLBACK_RECEIVE_PONG);
default:
break;
}
return NULL;
}
#if (LWS_LIBRARY_VERSION_MAJOR >= 4)
static lws_retry_bo_t pingpong = { 0 };
#endif
/* Helper method to return the interface associated with a local IP address */
static char *janus_websockets_get_interface_name(const char *ip) {
struct ifaddrs *addrs = NULL, *iap = NULL;
if(getifaddrs(&addrs) == -1)
return NULL;
for(iap = addrs; iap != NULL; iap = iap->ifa_next) {
if(iap->ifa_addr && (iap->ifa_flags & IFF_UP)) {
if(iap->ifa_addr->sa_family == AF_INET) {
struct sockaddr_in *sa = (struct sockaddr_in *)(iap->ifa_addr);
char buffer[16];
inet_ntop(iap->ifa_addr->sa_family, (void *)&(sa->sin_addr), buffer, sizeof(buffer));
if(!strcmp(ip, buffer)) {
char *iface = g_strdup(iap->ifa_name);
freeifaddrs(addrs);
return iface;
}
} else if(iap->ifa_addr->sa_family == AF_INET6) {
struct sockaddr_in6 *sa = (struct sockaddr_in6 *)(iap->ifa_addr);
char buffer[48];
inet_ntop(iap->ifa_addr->sa_family, (void *)&(sa->sin6_addr), buffer, sizeof(buffer));
if(!strcmp(ip, buffer)) {
char *iface = g_strdup(iap->ifa_name);
freeifaddrs(addrs);
return iface;
}
}
}
}
freeifaddrs(addrs);
return NULL;
}
/* Custom Access-Control-Allow-Origin value, if specified */
static char *allow_origin = NULL;
static gboolean enforce_cors = FALSE;
/* WebSockets ACL list for both Janus and Admin API */
static GList *janus_websockets_access_list = NULL, *janus_websockets_admin_access_list = NULL;
static janus_mutex access_list_mutex;
static void janus_websockets_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_websockets_access_list = g_list_append(janus_websockets_access_list, (gpointer)ip);
else
janus_websockets_admin_access_list = g_list_append(janus_websockets_admin_access_list, (gpointer)ip);
janus_mutex_unlock(&access_list_mutex);
}
static gboolean janus_websockets_is_allowed(const char *ip, gboolean admin) {
JANUS_LOG(LOG_VERB, "Checking if %s is allowed to contact %s interface\n", ip, admin ? "admin" : "janus");
if(ip == NULL)
return FALSE;
if(!admin && janus_websockets_access_list == NULL) {
JANUS_LOG(LOG_VERB, "Yep\n");
return TRUE;
}
if(admin && janus_websockets_admin_access_list == NULL) {
JANUS_LOG(LOG_VERB, "Yeah\n");
return TRUE;
}
janus_mutex_lock(&access_list_mutex);
GList *temp = admin ? janus_websockets_admin_access_list : janus_websockets_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);
JANUS_LOG(LOG_VERB, "Nope...\n");
return FALSE;
}
/* Transport implementation */
int janus_websockets_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;
}
#ifndef LWS_WITH_IPV6
JANUS_LOG(LOG_WARN, "libwebsockets has been built without IPv6 support, will bind to IPv4 only\n");
#endif
/* This is the callback we'll need to invoke to contact the Janus core */
gateway = callback;
/* Prepare the common context */
struct lws_context_creation_info wscinfo;
memset(&wscinfo, 0, sizeof wscinfo);
wscinfo.options |= LWS_SERVER_OPTION_EXPLICIT_VHOSTS;
/* We use vhosts on the same context to address both APIs, secure or not */
struct lws_vhost *wss = NULL, *swss = NULL,
*admin_wss = NULL, *admin_swss = NULL;
/* Read configuration */
char filename[255];
g_snprintf(filename, 255, "%s/%s.jcfg", config_path, JANUS_WEBSOCKETS_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_WEBSOCKETS_PACKAGE);
g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_WEBSOCKETS_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_WEBSOCKETS_NAME);
}
item = janus_config_get(config, config_general, janus_config_type_item, "ws_logging");
if(item && item->value) {
/* libwebsockets uses a mask to set log levels, as documented here:
* https://libwebsockets.org/lws-api-doc-master/html/group__log.html */
if(strstr(item->value, "none")) {
/* Disable libwebsockets logging completely (the default) */
} else if(strstr(item->value, "all")) {
/* Enable all libwebsockets logging */
ws_log_level = LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_INFO |
LLL_DEBUG | LLL_PARSER | LLL_HEADER | LLL_EXT |
#if (LWS_LIBRARY_VERSION_MAJOR >= 2 && LWS_LIBRARY_VERSION_MINOR >= 2) || (LWS_LIBRARY_VERSION_MAJOR >= 3)
LLL_CLIENT | LLL_LATENCY | LLL_USER | LLL_COUNT;
#else
LLL_CLIENT | LLL_LATENCY | LLL_COUNT;
#endif
} else {
/* Only enable some of the properties */
if(strstr(item->value, "err"))
ws_log_level |= LLL_ERR;
if(strstr(item->value, "warn"))
ws_log_level |= LLL_WARN;
if(strstr(item->value, "notice"))
ws_log_level |= LLL_NOTICE;
if(strstr(item->value, "info"))
ws_log_level |= LLL_INFO;
if(strstr(item->value, "debug"))
ws_log_level |= LLL_DEBUG;
if(strstr(item->value, "parser"))
ws_log_level |= LLL_PARSER;
if(strstr(item->value, "header"))
ws_log_level |= LLL_HEADER;
if(strstr(item->value, "ext"))
ws_log_level |= LLL_EXT;
if(strstr(item->value, "client"))
ws_log_level |= LLL_CLIENT;
if(strstr(item->value, "latency"))
ws_log_level |= LLL_LATENCY;
#if (LWS_LIBRARY_VERSION_MAJOR >= 2 && LWS_LIBRARY_VERSION_MINOR >= 2) || (LWS_LIBRARY_VERSION_MAJOR >= 3)
if(strstr(item->value, "user"))
ws_log_level |= LLL_USER;
#endif
if(strstr(item->value, "count"))
ws_log_level |= LLL_COUNT;
}
}
JANUS_LOG(LOG_INFO, "libwebsockets logging: %d\n", ws_log_level);
lws_set_log_level(ws_log_level, janus_websockets_log_emit_function);
/* Any ACL for either the Janus or Admin API? */
item = janus_config_get(config, config_general, janus_config_type_item, "ws_acl");
if(item && item->value) {
gchar **list = g_strsplit(item->value, ",", -1);
gchar *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_websockets_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_ws_acl");
if(item && item->value) {
gchar **list = g_strsplit(item->value, ",", -1);
gchar *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_websockets_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 rejecting WebSocket connections\n");
}
}
/* Check if we need to enable the transport level ping/pong mechanism */
int pingpong_trigger = 0, pingpong_timeout = 0;
item = janus_config_get(config, config_general, janus_config_type_item, "pingpong_trigger");
if(item && item->value) {
#if (LWS_LIBRARY_VERSION_MAJOR >= 2 && LWS_LIBRARY_VERSION_MINOR >= 1) || (LWS_LIBRARY_VERSION_MAJOR >= 3)
pingpong_trigger = atoi(item->value);
if(pingpong_trigger < 0) {
JANUS_LOG(LOG_WARN, "Invalid value for pingpong_trigger (%d), ignoring...\n", pingpong_trigger);
pingpong_trigger = 0;
}
#else
JANUS_LOG(LOG_WARN, "WebSockets ping/pong only supported in libwebsockets >= 2.1\n");
#endif
}
item = janus_config_get(config, config_general, janus_config_type_item, "pingpong_timeout");
if(item && item->value) {
#if (LWS_LIBRARY_VERSION_MAJOR >= 2 && LWS_LIBRARY_VERSION_MINOR >= 1) || (LWS_LIBRARY_VERSION_MAJOR >= 3)
pingpong_timeout = atoi(item->value);
if(pingpong_timeout < 0) {
JANUS_LOG(LOG_WARN, "Invalid value for pingpong_timeout (%d), ignoring...\n", pingpong_timeout);
pingpong_timeout = 0;
}
#else
JANUS_LOG(LOG_WARN, "WebSockets ping/pong only supported in libwebsockets >= 2.1\n");
#endif
}
if((pingpong_trigger && !pingpong_timeout) || (!pingpong_trigger && pingpong_timeout)) {
JANUS_LOG(LOG_WARN, "pingpong_trigger and pingpong_timeout not both set, ignoring...\n");
}
#if (LWS_LIBRARY_VERSION_MAJOR >= 4)
/* libwebsockets 4 has a different API, that works differently
* https://github.com/warmcat/libwebsockets/blob/master/READMEs/README.lws_retry.md */
if(pingpong_trigger > 0 && pingpong_timeout > 0) {
pingpong.secs_since_valid_ping = pingpong_trigger;
pingpong.secs_since_valid_hangup = pingpong_trigger + pingpong_timeout;
wscinfo.retry_and_idle_policy = &pingpong;
}
#else
#if (LWS_LIBRARY_VERSION_MAJOR >= 2 && LWS_LIBRARY_VERSION_MINOR >= 1) || (LWS_LIBRARY_VERSION_MAJOR == 3)
if(pingpong_trigger > 0 && pingpong_timeout > 0) {
wscinfo.ws_ping_pong_interval = pingpong_trigger;
wscinfo.timeout_secs = pingpong_timeout;
}
#endif
#endif
/* Force single-thread server */
wscinfo.count_threads = 1;
/* Create the base context */
wsc = lws_create_context(&wscinfo);
if(wsc == NULL) {
JANUS_LOG(LOG_ERR, "Error creating libwebsockets context...\n");
janus_config_destroy(config);
return -1; /* No point in keeping the plugin loaded */
}
/* Setup the Janus API WebSockets server(s) */
item = janus_config_get(config, config_general, janus_config_type_item, "ws");
if(!item || !item->value || !janus_is_true(item->value)) {
JANUS_LOG(LOG_VERB, "WebSockets server disabled\n");
} else {
uint16_t wsport = 8188;
item = janus_config_get(config, config_general, janus_config_type_item, "ws_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 = 8188;
}
char *interface = NULL;
item = janus_config_get(config, config_general, janus_config_type_item, "ws_interface");
if(item && item->value)
interface = (char *)item->value;
char *ip = NULL;
item = janus_config_get(config, config_general, janus_config_type_item, "ws_ip");
if(item && item->value) {
ip = (char *)item->value;
char *iface = janus_websockets_get_interface_name(ip);
if(iface == NULL) {
JANUS_LOG(LOG_WARN, "No interface associated with %s? Falling back to no interface...\n", ip);
}
ip = iface;
}
/* Prepare context */
struct lws_context_creation_info info;
memset(&info, 0, sizeof info);
info.port = wsport;
info.iface = ip ? ip : interface;
info.protocols = ws_protocols;
info.extensions = NULL;
info.ssl_cert_filepath = NULL;
info.ssl_private_key_filepath = NULL;
info.ssl_private_key_password = NULL;
info.gid = -1;
info.uid = -1;
#if (LWS_LIBRARY_VERSION_MAJOR == 3 && LWS_LIBRARY_VERSION_MINOR >= 2) || (LWS_LIBRARY_VERSION_MAJOR > 3)
info.options = LWS_SERVER_OPTION_FAIL_UPON_UNABLE_TO_BIND;
#endif
/* Create the WebSocket context */
wss = lws_create_vhost(wsc, &info);
if(wss == NULL) {
JANUS_LOG(LOG_FATAL, "Error creating vhost for WebSockets server...\n");
} else {
JANUS_LOG(LOG_INFO, "WebSockets server started (port %d)...\n", wsport);
}
g_free(ip);
}
item = janus_config_get(config, config_general, janus_config_type_item, "wss");
if(!item || !item->value || !janus_is_true(item->value)) {
JANUS_LOG(LOG_VERB, "Secure WebSockets server disabled\n");
} else {
uint16_t wsport = 8989;
item = janus_config_get(config, config_general, janus_config_type_item, "wss_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 = 8989;
}
char *interface = NULL;
item = janus_config_get(config, config_general, janus_config_type_item, "wss_interface");
if(item && item->value)
interface = (char *)item->value;
char *ip = NULL;
item = janus_config_get(config, config_general, janus_config_type_item, "wss_ip");
if(item && item->value) {
ip = (char *)item->value;
char *iface = janus_websockets_get_interface_name(ip);
if(iface == NULL) {
JANUS_LOG(LOG_WARN, "No interface associated with %s? Falling back to no interface...\n", ip);
}
ip = iface;
}
item = janus_config_get(config, config_certs, janus_config_type_item, "cert_pem");
if(!item || !item->value) {
JANUS_LOG(LOG_FATAL, "Missing certificate/key path\n");
} else {
char *server_pem = (char *)item->value;
char *server_key = (char *)item->value;
char *password = NULL;
char *ciphers = NULL;
item = janus_config_get(config, config_certs, janus_config_type_item, "cert_key");
if(item && item->value)
server_key = (char *)item->value;
item = janus_config_get(config, config_certs, janus_config_type_item, "cert_pwd");
if(item && item->value)
password = (char *)item->value;
JANUS_LOG(LOG_VERB, "Using certificates:\n\t%s\n\t%s\n", server_pem, server_key);
item = janus_config_get(config, config_certs, janus_config_type_item, "ciphers");
if(item && item->value)
ciphers = (char *)item->value;
/* Prepare secure context */
struct lws_context_creation_info info;
memset(&info, 0, sizeof info);
info.port = wsport;
info.iface = ip ? ip : interface;
info.protocols = sws_protocols;
info.extensions = NULL;
info.ssl_cert_filepath = server_pem;
info.ssl_private_key_filepath = server_key;
info.ssl_private_key_password = password;
info.ssl_cipher_list = ciphers;
info.gid = -1;
info.uid = -1;
#if (LWS_LIBRARY_VERSION_MAJOR == 3 && LWS_LIBRARY_VERSION_MINOR >= 2) || (LWS_LIBRARY_VERSION_MAJOR > 3)
info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT | LWS_SERVER_OPTION_FAIL_UPON_UNABLE_TO_BIND;
#elif LWS_LIBRARY_VERSION_MAJOR >= 2
info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
#endif
/* Create the secure WebSocket context */
swss = lws_create_vhost(wsc, &info);
if(swss == NULL) {
JANUS_LOG(LOG_FATAL, "Error creating vhost for Secure WebSockets server...\n");
} else {
JANUS_LOG(LOG_INFO, "Secure WebSockets server started (port %d)...\n", wsport);
}
}
g_free(ip);
}
/* Do the same for the Admin API, if enabled */
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_ws");
if(!item || !item->value || !janus_is_true(item->value)) {
JANUS_LOG(LOG_VERB, "Admin WebSockets server disabled\n");
} else {
uint16_t wsport = 7188;
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_ws_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 = 7188;
}
char *interface = NULL;
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_ws_interface");
if(item && item->value)
interface = (char *)item->value;
char *ip = NULL;
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_ws_ip");
if(item && item->value) {
ip = (char *)item->value;
char *iface = janus_websockets_get_interface_name(ip);
if(iface == NULL) {
JANUS_LOG(LOG_WARN, "No interface associated with %s? Falling back to no interface...\n", ip);
}
ip = iface;
}
/* Prepare context */
struct lws_context_creation_info info;
memset(&info, 0, sizeof info);
info.port = wsport;
info.iface = ip ? ip : interface;
info.protocols = admin_ws_protocols;
info.extensions = NULL;
info.ssl_cert_filepath = NULL;
info.ssl_private_key_filepath = NULL;
info.ssl_private_key_password = NULL;
info.gid = -1;
info.uid = -1;
#if (LWS_LIBRARY_VERSION_MAJOR == 3 && LWS_LIBRARY_VERSION_MINOR >= 2) || (LWS_LIBRARY_VERSION_MAJOR > 3)
info.options = LWS_SERVER_OPTION_FAIL_UPON_UNABLE_TO_BIND;
#endif
/* Create the WebSocket context */
admin_wss = lws_create_vhost(wsc, &info);
if(admin_wss == NULL) {
JANUS_LOG(LOG_FATAL, "Error creating vhost for Admin WebSockets server...\n");
} else {
JANUS_LOG(LOG_INFO, "Admin WebSockets server started (port %d)...\n", wsport);
}
g_free(ip);
}
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_wss");
if(!item || !item->value || !janus_is_true(item->value)) {
JANUS_LOG(LOG_VERB, "Secure Admin WebSockets server disabled\n");
} else {
uint16_t wsport = 7989;
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_wss_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 = 7989;
}
char *interface = NULL;
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_wss_interface");
if(item && item->value)
interface = (char *)item->value;
char *ip = NULL;
item = janus_config_get(config, config_admin, janus_config_type_item, "admin_wss_ip");
if(item && item->value) {
ip = (char *)item->value;
char *iface = janus_websockets_get_interface_name(ip);
if(iface == NULL) {
JANUS_LOG(LOG_WARN, "No interface associated with %s? Falling back to no interface...\n", ip);
}
ip = iface;
}
item = janus_config_get(config, config_certs, janus_config_type_item, "cert_pem");
if(!item || !item->value) {
JANUS_LOG(LOG_FATAL, "Missing certificate/key path\n");
} else {
char *server_pem = (char *)item->value;
char *server_key = (char *)item->value;
char *password = NULL;
char *ciphers = NULL;
item = janus_config_get(config, config_certs, janus_config_type_item, "cert_key");
if(item && item->value)
server_key = (char *)item->value;
item = janus_config_get(config, config_certs, janus_config_type_item, "cert_pwd");
if(item && item->value)
password = (char *)item->value;
JANUS_LOG(LOG_VERB, "Using certificates:\n\t%s\n\t%s\n", server_pem, server_key);
item = janus_config_get(config, config_certs, janus_config_type_item, "ciphers");
if(item && item->value)
ciphers = (char *)item->value;
/* Prepare secure context */
struct lws_context_creation_info info;
memset(&info, 0, sizeof info);
info.port = wsport;
info.iface = ip ? ip : interface;
info.protocols = admin_sws_protocols;
info.extensions = NULL;
info.ssl_cert_filepath = server_pem;
info.ssl_private_key_filepath = server_key;
info.ssl_private_key_password = password;
info.ssl_cipher_list = ciphers;
info.gid = -1;
info.uid = -1;
#if (LWS_LIBRARY_VERSION_MAJOR == 3 && LWS_LIBRARY_VERSION_MINOR >= 2) || (LWS_LIBRARY_VERSION_MAJOR > 3)
info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT | LWS_SERVER_OPTION_FAIL_UPON_UNABLE_TO_BIND;
#elif LWS_LIBRARY_VERSION_MAJOR >= 2
info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
#endif
/* Create the secure WebSocket context */
admin_swss = lws_create_vhost(wsc, &info);
if(admin_swss == NULL) {
JANUS_LOG(LOG_FATAL, "Error creating vhost for Secure Admin WebSockets server...\n");
} else {
JANUS_LOG(LOG_INFO, "Secure Admin WebSockets server started (port %d)...\n", wsport);
}
}
g_free(ip);
}
}
janus_config_destroy(config);
config = NULL;
if(!wss && !swss && !admin_wss && !admin_swss) {
JANUS_LOG(LOG_WARN, "No WebSockets server started, giving up...\n");
lws_context_destroy(wsc);
return -1; /* No point in keeping the plugin loaded */
}
ws_janus_api_enabled = wss || swss;
ws_admin_api_enabled = admin_wss || admin_swss;
#if (LWS_LIBRARY_VERSION_MAJOR >= 3)
clients = g_hash_table_new(NULL, NULL);
writable_clients = g_hash_table_new(NULL, NULL);
#endif
janus_mutex_init(&writable_mutex);
g_atomic_int_set(&initialized, 1);
GError *error = NULL;
/* Start the WebSocket service thread */
if(ws_janus_api_enabled || ws_admin_api_enabled) {
ws_thread = g_thread_try_new("ws thread", &janus_websockets_thread, wsc, &error);
if(error != NULL) {
g_atomic_int_set(&initialized, 0);
JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the WebSockets thread...\n",
error->code, error->message ? error->message : "??");
g_error_free(error);
return -1;
}
}
/* Done */
JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_WEBSOCKETS_NAME);
return 0;
}
void janus_websockets_destroy(void) {
if(!g_atomic_int_get(&initialized))
return;
g_atomic_int_set(&stopping, 1);
/* Stop the service thread */
if(ws_thread != NULL) {
g_thread_join(ws_thread);
ws_thread = NULL;
}
/* Destroy the context */
if(wsc != NULL) {
lws_context_destroy(wsc);
wsc = NULL;
}
#if (LWS_LIBRARY_VERSION_MAJOR >= 3)
janus_mutex_lock(&writable_mutex);
g_hash_table_destroy(clients);
clients = NULL;
g_hash_table_destroy(writable_clients);
writable_clients = NULL;
janus_mutex_unlock(&writable_mutex);
#endif
g_atomic_int_set(&initialized, 0);
g_atomic_int_set(&stopping, 0);
JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_WEBSOCKETS_NAME);
}
static void janus_websockets_destroy_client(
janus_websockets_client *ws_client,
struct lws *wsi,
const char *log_prefix) {
if(!ws_client || !ws_client->ts)
return;
janus_mutex_lock(&ws_client->ts->mutex);
if(!g_atomic_int_compare_and_exchange(&ws_client->destroyed, 0, 1)) {
janus_mutex_unlock(&ws_client->ts->mutex);
return;
}
/* Cleanup */
JANUS_LOG(LOG_INFO, "[%s-%p] Destroying WebSocket client\n", log_prefix, wsi);
#if (LWS_LIBRARY_VERSION_MAJOR >= 3)
janus_mutex_lock(&writable_mutex);
g_hash_table_remove(clients, ws_client);
g_hash_table_remove(writable_clients, ws_client);
janus_mutex_unlock(&writable_mutex);
#endif
ws_client->wsi = NULL;
/* Notify handlers about this transport being gone */
if(notify_events && gateway->events_is_enabled()) {
json_t *info = json_object();
json_object_set_new(info, "event", json_string("disconnected"));
gateway->notify_event(&janus_websockets_transport, ws_client->ts, info);
}
ws_client->ts->transport_p = NULL;
/* Remove messages queue too, if needed */
if(ws_client->messages != NULL) {
char *response = NULL;
while((response = g_async_queue_try_pop(ws_client->messages)) != NULL) {
g_free(response);
}
g_async_queue_unref(ws_client->messages);
}
/* ... and the shared buffers */
g_free(ws_client->incoming);
ws_client->incoming = NULL;
g_free(ws_client->buffer);
ws_client->buffer = NULL;
ws_client->buflen = 0;
ws_client->bufpending = 0;
ws_client->bufoffset = 0;
janus_mutex_unlock(&ws_client->ts->mutex);
/* Notify core */
gateway->transport_gone(&janus_websockets_transport, ws_client->ts);
janus_transport_session_destroy(ws_client->ts);
}
int janus_websockets_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_websockets_get_version(void) {
return JANUS_WEBSOCKETS_VERSION;
}
const char *janus_websockets_get_version_string(void) {
return JANUS_WEBSOCKETS_VERSION_STRING;
}
const char *janus_websockets_get_description(void) {
return JANUS_WEBSOCKETS_DESCRIPTION;
}
const char *janus_websockets_get_name(void) {
return JANUS_WEBSOCKETS_NAME;
}
const char *janus_websockets_get_author(void) {
return JANUS_WEBSOCKETS_AUTHOR;
}
const char *janus_websockets_get_package(void) {
return JANUS_WEBSOCKETS_PACKAGE;
}
gboolean janus_websockets_is_janus_api_enabled(void) {
return ws_janus_api_enabled;
}
gboolean janus_websockets_is_admin_api_enabled(void) {
return ws_admin_api_enabled;
}
int janus_websockets_send_message(janus_transport_session *transport, void *request_id, gboolean admin, json_t *message) {
if(message == NULL)
return -1;
if(transport == NULL || g_atomic_int_get(&transport->destroyed)) {
json_decref(message);
return -1;
}