Statistics
| Branch: | Revision:

janus-gateway / janus.c @ c63ddb33

History | View | Annotate | Download (181 KB)

1
/*! \file   janus.c
2
 * \author Lorenzo Miniero <lorenzo@meetecho.com>
3
 * \copyright GNU General Public License v3
4
 * \brief  Janus core
5
 * \details Implementation of the gateway core. This code takes care of
6
 * the gateway initialization (command line/configuration) and setup,
7
 * and makes use of the available transport plugins (by default HTTP,
8
 * WebSockets, RabbitMQ, if compiled) and Janus protocol (a JSON-based
9
 * protocol) to interact with the applications, whether they're web based
10
 * or not. The core also takes care of bridging peers and plugins
11
 * accordingly, in terms of both messaging and real-time media transfer
12
 * via WebRTC.
13
 *
14
 * \ingroup core
15
 * \ref core
16
 */
17

    
18
#include <dlfcn.h>
19
#include <dirent.h>
20
#include <net/if.h>
21
#include <netdb.h>
22
#include <signal.h>
23
#include <getopt.h>
24
#include <sys/resource.h>
25
#include <sys/stat.h>
26
#include <poll.h>
27

    
28
#include "janus.h"
29
#include "version.h"
30
#include "cmdline.h"
31
#include "config.h"
32
#include "apierror.h"
33
#include "log.h"
34
#include "debug.h"
35
#include "ip-utils.h"
36
#include "rtcp.h"
37
#include "auth.h"
38
#include "record.h"
39
#include "events.h"
40

    
41

    
42
#define JANUS_NAME                                "Janus WebRTC Gateway"
43
#define JANUS_AUTHOR                        "Meetecho s.r.l."
44
#define JANUS_VERSION                        23
45
#define JANUS_VERSION_STRING        "0.2.3"
46
#define JANUS_SERVER_NAME                "MyJanusInstance"
47

    
48
#ifdef __MACH__
49
#define SHLIB_EXT "0.dylib"
50
#else
51
#define SHLIB_EXT ".so"
52
#endif
53

    
54

    
55
static janus_config *config = NULL;
56
static char *config_file = NULL;
57
static char *configs_folder = NULL;
58

    
59
static GHashTable *transports = NULL;
60
static GHashTable *transports_so = NULL;
61

    
62
static GHashTable *eventhandlers = NULL;
63
static GHashTable *eventhandlers_so = NULL;
64

    
65
static GHashTable *plugins = NULL;
66
static GHashTable *plugins_so = NULL;
67

    
68

    
69
/* Daemonization */
70
static gboolean daemonize = FALSE;
71
static int pipefd[2];
72

    
73

    
74
/* API secrets */
75
static char *api_secret = NULL, *admin_api_secret = NULL;
76

    
77
/* JSON parameters */
78
static int janus_process_error_string(janus_request *request, uint64_t session_id, const char *transaction, gint error, gchar *error_string);
79

    
80
static struct janus_json_parameter incoming_request_parameters[] = {
81
        {"transaction", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
82
        {"janus", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
83
        {"id", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE}
84
};
85
static struct janus_json_parameter attach_parameters[] = {
86
        {"plugin", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
87
        {"opaque_id", JSON_STRING, 0}
88
};
89
static struct janus_json_parameter body_parameters[] = {
90
        {"body", JSON_OBJECT, JANUS_JSON_PARAM_REQUIRED}
91
};
92
static struct janus_json_parameter jsep_parameters[] = {
93
        {"type", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
94
        {"trickle", JANUS_JSON_BOOL, 0},
95
        {"sdp", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
96
};
97
static struct janus_json_parameter allow_token_parameters[] = {
98
        {"token", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
99
        {"plugins", JSON_ARRAY, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_NONEMPTY}
100
};
101
static struct janus_json_parameter add_token_parameters[] = {
102
        {"token", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
103
        {"plugins", JSON_ARRAY, 0}
104
};
105
static struct janus_json_parameter token_parameters[] = {
106
        {"token", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
107
};
108
static struct janus_json_parameter admin_parameters[] = {
109
        {"transaction", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
110
        {"janus", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
111
};
112
static struct janus_json_parameter debug_parameters[] = {
113
        {"debug", JANUS_JSON_BOOL, JANUS_JSON_PARAM_REQUIRED}
114
};
115
static struct janus_json_parameter timeout_parameters[] = {
116
        {"timeout", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE}
117
};
118
static struct janus_json_parameter level_parameters[] = {
119
        {"level", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE}
120
};
121
static struct janus_json_parameter timestamps_parameters[] = {
122
        {"timestamps", JANUS_JSON_BOOL, JANUS_JSON_PARAM_REQUIRED}
123
};
124
static struct janus_json_parameter colors_parameters[] = {
125
        {"colors", JANUS_JSON_BOOL, JANUS_JSON_PARAM_REQUIRED}
126
};
127
static struct janus_json_parameter mnq_parameters[] = {
128
        {"max_nack_queue", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE}
129
};
130
static struct janus_json_parameter nmt_parameters[] = {
131
        {"no_media_timer", JSON_INTEGER, JANUS_JSON_PARAM_REQUIRED | JANUS_JSON_PARAM_POSITIVE}
132
};
133

    
134
/* Admin/Monitor helpers */
135
json_t *janus_admin_stream_summary(janus_ice_stream *stream);
136
json_t *janus_admin_component_summary(janus_ice_component *component);
137

    
138

    
139
/* IP addresses */
140
static gchar *local_ip = NULL;
141
gchar *janus_get_local_ip(void) {
142
        return local_ip;
143
}
144
static gchar *public_ip = NULL;
145
gchar *janus_get_public_ip(void) {
146
        /* Fallback to the local IP, if we have no public one */
147
        return public_ip ? public_ip : local_ip;
148
}
149
void janus_set_public_ip(const char *ip) {
150
        /* once set do not override */
151
        if(ip == NULL || public_ip != NULL)
152
                return;
153
        public_ip = g_strdup(ip);
154
}
155
static volatile gint stop = 0;
156
static gint stop_signal = 0;
157
gint janus_is_stopping(void) {
158
        return g_atomic_int_get(&stop);
159
}
160

    
161

    
162
/* Public instance name */
163
static gchar *server_name = NULL;
164

    
165

    
166
/* The default timeout for sessions is 60 seconds: this means that, if
167
 * we don't get any activity (i.e., no request) on this session for more
168
 * than 60 seconds, then it's considered expired and we destroy it. That's
169
 * why we have a keep-alive method in the API. This can be overridden in
170
 * either janus.cfg or from the command line. Setting this to 0 will
171
 * disable the timeout mechanism, which is NOT suggested as it may risk
172
 * having orphaned sessions (sessions not controlled by any transport
173
 * and never freed). Besides, notice that if you make this shorter than
174
 * 30s, you'll have to update the timers in janus.js when the long
175
 * polling mechanism is used and shorten them as well, or you'll risk
176
 * incurring in unexpected timeouts (when HTTP is used in janus.js, the
177
 * long poll is used as a keepalive mechanism). */
178
#define DEFAULT_SESSION_TIMEOUT                60
179
static uint session_timeout = DEFAULT_SESSION_TIMEOUT;
180

    
181

    
182
/* Information */
183
static json_t *janus_info(const char *transaction) {
184
        /* Prepare a summary on the gateway */
185
        json_t *info = json_object();
186
        json_object_set_new(info, "janus", json_string("server_info"));
187
        if(transaction != NULL)
188
                json_object_set_new(info, "transaction", json_string(transaction));
189
        json_object_set_new(info, "name", json_string(JANUS_NAME));
190
        json_object_set_new(info, "version", json_integer(JANUS_VERSION));
191
        json_object_set_new(info, "version_string", json_string(JANUS_VERSION_STRING));
192
        json_object_set_new(info, "author", json_string(JANUS_AUTHOR));
193
        json_object_set_new(info, "commit-hash", json_string(janus_build_git_sha));
194
        json_object_set_new(info, "compile-time", json_string(janus_build_git_time));
195
        json_object_set_new(info, "log-to-stdout", janus_log_is_stdout_enabled() ? json_true() : json_false());
196
        json_object_set_new(info, "log-to-file", janus_log_is_logfile_enabled() ? json_true() : json_false());
197
        if(janus_log_is_logfile_enabled())
198
                json_object_set_new(info, "log-path", json_string(janus_log_get_logfile_path()));
199
#ifdef HAVE_SCTP
200
        json_object_set_new(info, "data_channels", json_true());
201
#else
202
        json_object_set_new(info, "data_channels", json_false());
203
#endif
204
        json_object_set_new(info, "session-timeout", json_integer(session_timeout));
205
        json_object_set_new(info, "server-name", json_string(server_name ? server_name : JANUS_SERVER_NAME));
206
        json_object_set_new(info, "local-ip", json_string(local_ip));
207
        if(public_ip != NULL)
208
                json_object_set_new(info, "public-ip", json_string(public_ip));
209
        json_object_set_new(info, "ipv6", janus_ice_is_ipv6_enabled() ? json_true() : json_false());
210
        json_object_set_new(info, "ice-lite", janus_ice_is_ice_lite_enabled() ? json_true() : json_false());
211
        json_object_set_new(info, "ice-tcp", janus_ice_is_ice_tcp_enabled() ? json_true() : json_false());
212
        if(janus_ice_get_stun_server() != NULL) {
213
                char server[255];
214
                g_snprintf(server, 255, "%s:%"SCNu16, janus_ice_get_stun_server(), janus_ice_get_stun_port());
215
                json_object_set_new(info, "stun-server", json_string(server));
216
        }
217
        if(janus_ice_get_turn_server() != NULL) {
218
                char server[255];
219
                g_snprintf(server, 255, "%s:%"SCNu16, janus_ice_get_turn_server(), janus_ice_get_turn_port());
220
                json_object_set_new(info, "turn-server", json_string(server));
221
        }
222
        json_object_set_new(info, "api_secret", api_secret ? json_true() : json_false());
223
        json_object_set_new(info, "auth_token", janus_auth_is_enabled() ? json_true() : json_false());
224
        json_object_set_new(info, "event_handlers", janus_events_is_enabled() ? json_true() : json_false());
225
        /* Available transports */
226
        json_t *t_data = json_object();
227
        if(transports && g_hash_table_size(transports) > 0) {
228
                GHashTableIter iter;
229
                gpointer value;
230
                g_hash_table_iter_init(&iter, transports);
231
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
232
                        janus_transport *t = value;
233
                        if(t == NULL) {
234
                                continue;
235
                        }
236
                        json_t *transport = json_object();
237
                        json_object_set_new(transport, "name", json_string(t->get_name()));
238
                        json_object_set_new(transport, "author", json_string(t->get_author()));
239
                        json_object_set_new(transport, "description", json_string(t->get_description()));
240
                        json_object_set_new(transport, "version_string", json_string(t->get_version_string()));
241
                        json_object_set_new(transport, "version", json_integer(t->get_version()));
242
                        json_object_set_new(t_data, t->get_package(), transport);
243
                }
244
        }
245
        json_object_set_new(info, "transports", t_data);
246
        /* Available event handlers */
247
        json_t *e_data = json_object();
248
        if(eventhandlers && g_hash_table_size(eventhandlers) > 0) {
249
                GHashTableIter iter;
250
                gpointer value;
251
                g_hash_table_iter_init(&iter, eventhandlers);
252
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
253
                        janus_eventhandler *e = value;
254
                        if(e == NULL) {
255
                                continue;
256
                        }
257
                        json_t *eventhandler = json_object();
258
                        json_object_set_new(eventhandler, "name", json_string(e->get_name()));
259
                        json_object_set_new(eventhandler, "author", json_string(e->get_author()));
260
                        json_object_set_new(eventhandler, "description", json_string(e->get_description()));
261
                        json_object_set_new(eventhandler, "version_string", json_string(e->get_version_string()));
262
                        json_object_set_new(eventhandler, "version", json_integer(e->get_version()));
263
                        json_object_set_new(e_data, e->get_package(), eventhandler);
264
                }
265
        }
266
        json_object_set_new(info, "events", e_data);
267
        /* Available plugins */
268
        json_t *p_data = json_object();
269
        if(plugins && g_hash_table_size(plugins) > 0) {
270
                GHashTableIter iter;
271
                gpointer value;
272
                g_hash_table_iter_init(&iter, plugins);
273
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
274
                        janus_plugin *p = value;
275
                        if(p == NULL) {
276
                                continue;
277
                        }
278
                        json_t *plugin = json_object();
279
                        json_object_set_new(plugin, "name", json_string(p->get_name()));
280
                        json_object_set_new(plugin, "author", json_string(p->get_author()));
281
                        json_object_set_new(plugin, "description", json_string(p->get_description()));
282
                        json_object_set_new(plugin, "version_string", json_string(p->get_version_string()));
283
                        json_object_set_new(plugin, "version", json_integer(p->get_version()));
284
                        json_object_set_new(p_data, p->get_package(), plugin);
285
                }
286
        }
287
        json_object_set_new(info, "plugins", p_data);
288

    
289
        return info;
290
}
291

    
292

    
293
/* Logging */
294
int janus_log_level = LOG_INFO;
295
gboolean janus_log_timestamps = FALSE;
296
gboolean janus_log_colors = FALSE;
297
int lock_debug = 0;
298

    
299

    
300
/*! \brief Signal handler (just used to intercept CTRL+C and SIGTERM) */
301
static void janus_handle_signal(int signum) {
302
        stop_signal = signum;
303
        switch(g_atomic_int_get(&stop)) {
304
                case 0:
305
                        JANUS_PRINT("Stopping gateway, please wait...\n");
306
                        break;
307
                case 1:
308
                        JANUS_PRINT("In a hurry? I'm trying to free resources cleanly, here!\n");
309
                        break;
310
                default:
311
                        JANUS_PRINT("Ok, leaving immediately...\n");
312
                        break;
313
        }
314
        g_atomic_int_inc(&stop);
315
        if(g_atomic_int_get(&stop) > 2)
316
                exit(1);
317
}
318

    
319
/*! \brief Termination handler (atexit) */
320
static void janus_termination_handler(void) {
321
        /* Free the instance name, if provided */
322
        g_free(server_name);
323
        /* Remove the PID file if we created it */
324
        janus_pidfile_remove();
325
        /* Close the logger */
326
        janus_log_destroy();
327
        /* If we're daemonizing, we send an error code to the parent */
328
        if(daemonize) {
329
                int code = 1;
330
                ssize_t res = 0;
331
                do {
332
                        res = write(pipefd[1], &code, sizeof(int));
333
                } while(res == -1 && errno == EINTR);
334
        }
335
}
336

    
337

    
338
/** @name Transport plugin callback interface
339
 * These are the callbacks implemented by the gateway core, as part of
340
 * the janus_transport_callbacks interface. Everything the transport
341
 * plugins send the gateway is handled here.
342
 */
343
///@{
344
void janus_transport_incoming_request(janus_transport *plugin, void *transport, void *request_id, gboolean admin, json_t *message, json_error_t *error);
345
void janus_transport_gone(janus_transport *plugin, void *transport);
346
gboolean janus_transport_is_api_secret_needed(janus_transport *plugin);
347
gboolean janus_transport_is_api_secret_valid(janus_transport *plugin, const char *apisecret);
348
gboolean janus_transport_is_auth_token_needed(janus_transport *plugin);
349
gboolean janus_transport_is_auth_token_valid(janus_transport *plugin, const char *token);
350
void janus_transport_notify_event(janus_transport *plugin, void *transport, json_t *event);
351

    
352
static janus_transport_callbacks janus_handler_transport =
353
        {
354
                .incoming_request = janus_transport_incoming_request,
355
                .transport_gone = janus_transport_gone,
356
                .is_api_secret_needed = janus_transport_is_api_secret_needed,
357
                .is_api_secret_valid = janus_transport_is_api_secret_valid,
358
                .is_auth_token_needed = janus_transport_is_auth_token_needed,
359
                .is_auth_token_valid = janus_transport_is_auth_token_valid,
360
                .events_is_enabled = janus_events_is_enabled,
361
                .notify_event = janus_transport_notify_event,
362
        };
363
GThreadPool *tasks = NULL;
364
void janus_transport_task(gpointer data, gpointer user_data);
365
///@}
366

    
367

    
368
/** @name Plugin callback interface
369
 * These are the callbacks implemented by the gateway core, as part of
370
 * the janus_callbacks interface. Everything the plugins send the
371
 * gateway is handled here.
372
 */
373
///@{
374
int janus_plugin_push_event(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *transaction, json_t *message, json_t *jsep);
375
json_t *janus_plugin_handle_sdp(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *sdp_type, const char *sdp);
376
void janus_plugin_relay_rtp(janus_plugin_session *plugin_session, int video, char *buf, int len);
377
void janus_plugin_relay_rtcp(janus_plugin_session *plugin_session, int video, char *buf, int len);
378
void janus_plugin_relay_data(janus_plugin_session *plugin_session, char *buf, int len);
379
void janus_plugin_close_pc(janus_plugin_session *plugin_session);
380
void janus_plugin_end_session(janus_plugin_session *plugin_session);
381
void janus_plugin_notify_event(janus_plugin *plugin, janus_plugin_session *plugin_session, json_t *event);
382
static janus_callbacks janus_handler_plugin =
383
        {
384
                .push_event = janus_plugin_push_event,
385
                .relay_rtp = janus_plugin_relay_rtp,
386
                .relay_rtcp = janus_plugin_relay_rtcp,
387
                .relay_data = janus_plugin_relay_data,
388
                .close_pc = janus_plugin_close_pc,
389
                .end_session = janus_plugin_end_session,
390
                .events_is_enabled = janus_events_is_enabled,
391
                .notify_event = janus_plugin_notify_event,
392
        }; 
393
///@}
394

    
395

    
396
/* Gateway Sessions */
397
static janus_mutex sessions_mutex;
398
static GHashTable *sessions = NULL, *old_sessions = NULL;
399
static GMainContext *sessions_watchdog_context = NULL;
400

    
401

    
402
static gboolean janus_cleanup_session(gpointer user_data) {
403
        janus_session *session = (janus_session *) user_data;
404

    
405
        JANUS_LOG(LOG_DBG, "Cleaning up session %"SCNu64"...\n", session->session_id);
406
        janus_session_destroy(session->session_id);
407

    
408
        return G_SOURCE_REMOVE;
409
}
410

    
411
static gboolean janus_check_sessions(gpointer user_data) {
412
        if(session_timeout < 1)                /* Session timeouts are disabled */
413
                return G_SOURCE_CONTINUE;
414
        GMainContext *watchdog_context = (GMainContext *) user_data;
415
        janus_mutex_lock(&sessions_mutex);
416
        if(sessions && g_hash_table_size(sessions) > 0) {
417
                GHashTableIter iter;
418
                gpointer value;
419
                g_hash_table_iter_init(&iter, sessions);
420
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
421
                        janus_session *session = (janus_session *) value;
422
                        if (!session || session->destroy) {
423
                                continue;
424
                        }
425
                        gint64 now = janus_get_monotonic_time();
426
                        if (now - session->last_activity >= session_timeout * G_USEC_PER_SEC && !session->timeout) {
427
                                JANUS_LOG(LOG_INFO, "Timeout expired for session %"SCNu64"...\n", session->session_id);
428

    
429
                                /* Notify the transport */
430
                                if(session->source) {
431
                                        json_t *event = json_object();
432
                                        json_object_set_new(event, "janus", json_string("timeout"));
433
                                        json_object_set_new(event, "session_id", json_integer(session->session_id));
434
                                        /* Send this to the transport client */
435
                                        session->source->transport->send_message(session->source->instance, NULL, FALSE, event);
436
                                        /* Notify the transport plugin about the session timeout */
437
                                        session->source->transport->session_over(session->source->instance, session->session_id, TRUE);
438
                                }
439
                                /* Notify event handlers as well */
440
                                if(janus_events_is_enabled())
441
                                        janus_events_notify_handlers(JANUS_EVENT_TYPE_SESSION, session->session_id, "timeout", NULL);
442

    
443
                                /* Mark the session as over, we'll deal with it later */
444
                                session->timeout = 1;
445
                                /* FIXME Is this safe? apparently it causes hash table errors on the console */
446
                                g_hash_table_iter_remove(&iter);
447
                                g_hash_table_insert(old_sessions, janus_uint64_dup(session->session_id), session);
448

    
449
                                /* Schedule the session for deletion */
450
                                GSource *timeout_source = g_timeout_source_new_seconds(3);
451
                                g_source_set_callback(timeout_source, janus_cleanup_session, session, NULL);
452
                                g_source_attach(timeout_source, watchdog_context);
453
                                g_source_unref(timeout_source);
454
                        }
455
                }
456
        }
457
        janus_mutex_unlock(&sessions_mutex);
458

    
459
        return G_SOURCE_CONTINUE;
460
}
461

    
462
static gpointer janus_sessions_watchdog(gpointer user_data) {
463
        GMainLoop *loop = (GMainLoop *) user_data;
464
        GMainContext *watchdog_context = g_main_loop_get_context(loop);
465
        GSource *timeout_source;
466

    
467
        timeout_source = g_timeout_source_new_seconds(2);
468
        g_source_set_callback(timeout_source, janus_check_sessions, watchdog_context, NULL);
469
        g_source_attach(timeout_source, watchdog_context);
470
        g_source_unref(timeout_source);
471

    
472
        JANUS_LOG(LOG_INFO, "Sessions watchdog started\n");
473

    
474
        g_main_loop_run(loop);
475

    
476
        return NULL;
477
}
478

    
479
janus_session *janus_session_create(guint64 session_id) {
480
        if(session_id == 0) {
481
                while(session_id == 0) {
482
                        session_id = janus_random_uint64();
483
                        if(janus_session_find(session_id) != NULL) {
484
                                /* Session ID already taken, try another one */
485
                                session_id = 0;
486
                        }
487
                }
488
        }
489
        JANUS_LOG(LOG_INFO, "Creating new session: %"SCNu64"\n", session_id);
490
        janus_session *session = (janus_session *)g_malloc0(sizeof(janus_session));
491
        if(session == NULL) {
492
                JANUS_LOG(LOG_FATAL, "Memory error!\n");
493
                return NULL;
494
        }
495
        session->session_id = session_id;
496
        session->source = NULL;
497
        session->destroy = 0;
498
        session->timeout = 0;
499
        session->last_activity = janus_get_monotonic_time();
500
        janus_mutex_init(&session->mutex);
501
        janus_mutex_lock(&sessions_mutex);
502
        g_hash_table_insert(sessions, janus_uint64_dup(session->session_id), session);
503
        janus_mutex_unlock(&sessions_mutex);
504
        return session;
505
}
506

    
507
janus_session *janus_session_find(guint64 session_id) {
508
        janus_mutex_lock(&sessions_mutex);
509
        janus_session *session = g_hash_table_lookup(sessions, &session_id);
510
        janus_mutex_unlock(&sessions_mutex);
511
        return session;
512
}
513

    
514
janus_session *janus_session_find_destroyed(guint64 session_id) {
515
        janus_mutex_lock(&sessions_mutex);
516
        janus_session *session = g_hash_table_lookup(old_sessions, &session_id);
517
        janus_mutex_unlock(&sessions_mutex);
518
        return session;
519
}
520

    
521
void janus_session_notify_event(guint64 session_id, json_t *event) {
522
        janus_mutex_lock(&sessions_mutex);
523
        janus_session *session = sessions ? g_hash_table_lookup(sessions, &session_id) : NULL;
524
        if(session != NULL && !session->destroy && session->source != NULL && session->source->transport != NULL) {
525
                janus_mutex_unlock(&sessions_mutex);
526
                /* Send this to the transport client */
527
                JANUS_LOG(LOG_HUGE, "Sending event to %s (%p)\n", session->source->transport->get_package(), session->source->instance);
528
                session->source->transport->send_message(session->source->instance, NULL, FALSE, event);
529
        } else {
530
                janus_mutex_unlock(&sessions_mutex);
531
                /* No transport, free the event */
532
                json_decref(event);
533
        }
534
}
535

    
536

    
537
/* Destroys a session but does not remove it from the sessions hash table. */
538
gint janus_session_destroy(guint64 session_id) {
539
        janus_session *session = janus_session_find_destroyed(session_id);
540
        if(session == NULL) {
541
                JANUS_LOG(LOG_ERR, "Couldn't find session to destroy: %"SCNu64"\n", session_id);
542
                return -1;
543
        }
544
        JANUS_LOG(LOG_VERB, "Destroying session %"SCNu64"\n", session_id);
545
        session->destroy = 1;
546
        if (session->ice_handles != NULL && g_hash_table_size(session->ice_handles) > 0) {
547
                GHashTableIter iter;
548
                gpointer value;
549
                /* Remove all handles */
550
                g_hash_table_iter_init(&iter, session->ice_handles);
551
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
552
                        janus_ice_handle *handle = value;
553
                        if(!handle || g_atomic_int_get(&stop)) {
554
                                continue;
555
                        }
556
                        janus_ice_handle_destroy(session, handle->handle_id);
557
                        g_hash_table_iter_remove(&iter);
558
                }
559
        }
560

    
561
        /* FIXME Actually destroy session */
562
        janus_session_free(session);
563

    
564
        return 0;
565
}
566

    
567
void janus_session_free(janus_session *session) {
568
        if(session == NULL)
569
                return;
570
        janus_mutex_lock(&session->mutex);
571
        if(session->ice_handles != NULL) {
572
                g_hash_table_destroy(session->ice_handles);
573
                session->ice_handles = NULL;
574
        }
575
        if(session->source != NULL) {
576
                janus_request_destroy(session->source);
577
                session->source = NULL;
578
        }
579
        janus_mutex_unlock(&session->mutex);
580
        g_free(session);
581
        session = NULL;
582
}
583

    
584

    
585
/* Requests management */
586
janus_request *janus_request_new(janus_transport *transport, void *instance, void *request_id, gboolean admin, json_t *message) {
587
        janus_request *request = (janus_request *)g_malloc0(sizeof(janus_request));
588
        request->transport = transport;
589
        request->instance = instance;
590
        request->request_id = request_id;
591
        request->admin = admin;
592
        request->message = message;
593
        return request;
594
}
595

    
596
void janus_request_destroy(janus_request *request) {
597
        if(request == NULL)
598
                return;
599
        request->transport = NULL;
600
        request->instance = NULL;
601
        request->request_id = NULL;
602
        if(request->message)
603
                json_decref(request->message);
604
        request->message = NULL;
605
        g_free(request);
606
}
607

    
608
int janus_process_incoming_request(janus_request *request) {
609
        int ret = -1;
610
        if(request == NULL) {
611
                JANUS_LOG(LOG_ERR, "Missing request or payload to process, giving up...\n");
612
                return ret;
613
        }
614
        int error_code = 0;
615
        char error_cause[100];
616
        json_t *root = request->message;
617
        /* Ok, let's start with the ids */
618
        guint64 session_id = 0, handle_id = 0;
619
        json_t *s = json_object_get(root, "session_id");
620
        if(s && json_is_integer(s))
621
                session_id = json_integer_value(s);
622
        json_t *h = json_object_get(root, "handle_id");
623
        if(h && json_is_integer(h))
624
                handle_id = json_integer_value(h);
625

    
626
        /* Get transaction and message request */
627
        JANUS_VALIDATE_JSON_OBJECT(root, incoming_request_parameters,
628
                error_code, error_cause, FALSE,
629
                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
630
        if(error_code != 0) {
631
                ret = janus_process_error_string(request, session_id, NULL, error_code, error_cause);
632
                goto jsondone;
633
        }
634
        json_t *transaction = json_object_get(root, "transaction");
635
        const gchar *transaction_text = json_string_value(transaction);
636
        json_t *message = json_object_get(root, "janus");
637
        const gchar *message_text = json_string_value(message);
638

    
639
        if(session_id == 0 && handle_id == 0) {
640
                /* Can only be a 'Create new session', a 'Get info' or a 'Ping/Pong' request */
641
                if(!strcasecmp(message_text, "info")) {
642
                        ret = janus_process_success(request, janus_info(transaction_text));
643
                        goto jsondone;
644
                }
645
                if(!strcasecmp(message_text, "ping")) {
646
                        /* Prepare JSON reply */
647
                        json_t *reply = json_object();
648
                        json_object_set_new(reply, "janus", json_string("pong"));
649
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
650
                        ret = janus_process_success(request, reply);
651
                        goto jsondone;
652
                }
653
                if(strcasecmp(message_text, "create")) {
654
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
655
                        goto jsondone;
656
                }
657
                /* Any secret/token to check? */
658
                gboolean secret_authorized = FALSE, token_authorized = FALSE;
659
                if(api_secret == NULL && !janus_auth_is_enabled()) {
660
                        /* Nothing to check */
661
                        secret_authorized = TRUE;
662
                        token_authorized = TRUE;
663
                } else {
664
                        if(api_secret != NULL) {
665
                                /* There's an API secret, check that the client provided it */
666
                                json_t *secret = json_object_get(root, "apisecret");
667
                                if(secret && json_is_string(secret) && janus_strcmp_const_time(json_string_value(secret), api_secret)) {
668
                                        secret_authorized = TRUE;
669
                                }
670
                        }
671
                        if(janus_auth_is_enabled()) {
672
                                /* The token based authentication mechanism is enabled, check that the client provided it */
673
                                json_t *token = json_object_get(root, "token");
674
                                if(token && json_is_string(token) && janus_auth_check_token(json_string_value(token))) {
675
                                        token_authorized = TRUE;
676
                                }
677
                        }
678
                        /* We consider a request authorized if either the proper API secret or a valid token has been provided */
679
                        if(!secret_authorized && !token_authorized) {
680
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNAUTHORIZED, NULL);
681
                                goto jsondone;
682
                        }
683
                }
684
                session_id = 0;
685
                json_t *id = json_object_get(root, "id");
686
                if(id != NULL) {
687
                        /* The application provided the session ID to use */
688
                        session_id = json_integer_value(id);
689
                        if(session_id > 0 && janus_session_find(session_id) != NULL) {
690
                                /* Session ID already taken */
691
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_CONFLICT, "Session ID already in use");
692
                                goto jsondone;
693
                        }
694
                }
695
                /* Handle it */
696
                janus_session *session = janus_session_create(session_id);
697
                if(session == NULL) {
698
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN, "Memory error");
699
                        goto jsondone;
700
                }
701
                session_id = session->session_id;
702
                /* Take note of the request source that originated this session (HTTP, WebSockets, RabbitMQ?) */
703
                session->source = janus_request_new(request->transport, request->instance, NULL, FALSE, NULL);
704
                /* Notify the source that a new session has been created */
705
                request->transport->session_created(request->instance, session->session_id);
706
                /* Notify event handlers */
707
                if(janus_events_is_enabled()) {
708
                        /* Session created, add info on the transport that originated it */
709
                        json_t *transport = json_object();
710
                        json_object_set_new(transport, "transport", json_string(session->source->transport->get_package()));
711
                        char id[32];
712
                        memset(id, 0, sizeof(id));
713
                        g_snprintf(id, sizeof(id), "%p", session->source->instance);
714
                        json_object_set_new(transport, "id", json_string(id));
715
                        janus_events_notify_handlers(JANUS_EVENT_TYPE_SESSION, session_id, "created", transport);
716
                }
717
                /* Prepare JSON reply */
718
                json_t *reply = json_object();
719
                json_object_set_new(reply, "janus", json_string("success"));
720
                json_object_set_new(reply, "transaction", json_string(transaction_text));
721
                json_t *data = json_object();
722
                json_object_set_new(data, "id", json_integer(session_id));
723
                json_object_set_new(reply, "data", data);
724
                /* Send the success reply */
725
                ret = janus_process_success(request, reply);
726
                goto jsondone;
727
        }
728
        if(session_id < 1) {
729
                JANUS_LOG(LOG_ERR, "Invalid session\n");
730
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, NULL);
731
                goto jsondone;
732
        }
733
        if(h && handle_id < 1) {
734
                JANUS_LOG(LOG_ERR, "Invalid handle\n");
735
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, NULL);
736
                goto jsondone;
737
        }
738

    
739
        /* Go on with the processing */
740
        gboolean secret_authorized = FALSE, token_authorized = FALSE;
741
        if(api_secret == NULL && !janus_auth_is_enabled()) {
742
                /* Nothing to check */
743
                secret_authorized = TRUE;
744
                token_authorized = TRUE;
745
        } else {
746
                if(api_secret != NULL) {
747
                        /* There's an API secret, check that the client provided it */
748
                        json_t *secret = json_object_get(root, "apisecret");
749
                        if(secret && json_is_string(secret) && janus_strcmp_const_time(json_string_value(secret), api_secret)) {
750
                                secret_authorized = TRUE;
751
                        }
752
                }
753
                if(janus_auth_is_enabled()) {
754
                        /* The token based authentication mechanism is enabled, check that the client provided it */
755
                        json_t *token = json_object_get(root, "token");
756
                        if(token && json_is_string(token) && janus_auth_check_token(json_string_value(token))) {
757
                                token_authorized = TRUE;
758
                        }
759
                }
760
                /* We consider a request authorized if either the proper API secret or a valid token has been provided */
761
                if(!secret_authorized && !token_authorized) {
762
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNAUTHORIZED, NULL);
763
                        goto jsondone;
764
                }
765
        }
766

    
767
        /* If we got here, make sure we have a session (and/or a handle) */
768
        janus_session *session = janus_session_find(session_id);
769
        if(!session) {
770
                JANUS_LOG(LOG_ERR, "Couldn't find any session %"SCNu64"...\n", session_id);
771
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, "No such session %"SCNu64"", session_id);
772
                goto jsondone;
773
        }
774
        /* Update the last activity timer */
775
        session->last_activity = janus_get_monotonic_time();
776
        janus_ice_handle *handle = NULL;
777
        if(handle_id > 0) {
778
                handle = janus_ice_handle_find(session, handle_id);
779
                if(!handle) {
780
                        JANUS_LOG(LOG_ERR, "Couldn't find any handle %"SCNu64" in session %"SCNu64"...\n", handle_id, session_id);
781
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_HANDLE_NOT_FOUND, "No such handle %"SCNu64" in session %"SCNu64"", handle_id, session_id);
782
                        goto jsondone;
783
                }
784
        }
785

    
786
        /* What is this? */
787
        if(!strcasecmp(message_text, "keepalive")) {
788
                /* Just a keep-alive message, reply with an ack */
789
                JANUS_LOG(LOG_VERB, "Got a keep-alive on session %"SCNu64"\n", session_id);
790
                json_t *reply = json_object();
791
                json_object_set_new(reply, "janus", json_string("ack"));
792
                json_object_set_new(reply, "session_id", json_integer(session_id));
793
                json_object_set_new(reply, "transaction", json_string(transaction_text));
794
                /* Send the success reply */
795
                ret = janus_process_success(request, reply);
796
        } else if(!strcasecmp(message_text, "attach")) {
797
                if(handle != NULL) {
798
                        /* Attach is a session-level command */
799
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
800
                        goto jsondone;
801
                }
802
                JANUS_VALIDATE_JSON_OBJECT(root, attach_parameters,
803
                        error_code, error_cause, FALSE,
804
                        JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
805
                if(error_code != 0) {
806
                        ret = janus_process_error_string(request, session_id, NULL, error_code, error_cause);
807
                        goto jsondone;
808
                }
809
                json_t *plugin = json_object_get(root, "plugin");
810
                const gchar *plugin_text = json_string_value(plugin);
811
                janus_plugin *plugin_t = janus_plugin_find(plugin_text);
812
                if(plugin_t == NULL) {
813
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_NOT_FOUND, "No such plugin '%s'", plugin_text);
814
                        goto jsondone;
815
                }
816
                /* If the auth token mechanism is enabled, we should check if this token can access this plugin */
817
                if(janus_auth_is_enabled()) {
818
                        json_t *token = json_object_get(root, "token");
819
                        if(token != NULL) {
820
                                const char *token_value = json_string_value(token);
821
                                if(token_value && !janus_auth_check_plugin(token_value, plugin_t)) {
822
                                        JANUS_LOG(LOG_ERR, "Token '%s' can't access plugin '%s'\n", token_value, plugin_text);
823
                                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNAUTHORIZED_PLUGIN, "Provided token can't access plugin '%s'", plugin_text);
824
                                        goto jsondone;
825
                                }
826
                        }
827
                }
828
                json_t *opaque = json_object_get(root, "opaque_id");
829
                const char *opaque_id = opaque ? json_string_value(opaque) : NULL;
830
                /* Create handle */
831
                handle = janus_ice_handle_create(session, opaque_id);
832
                if(handle == NULL) {
833
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN, "Memory error");
834
                        goto jsondone;
835
                }
836
                handle_id = handle->handle_id;
837
                /* Attach to the plugin */
838
                int error = 0;
839
                if((error = janus_ice_handle_attach_plugin(session, handle_id, plugin_t)) != 0) {
840
                        /* TODO Make error struct to pass verbose information */
841
                        janus_ice_handle_destroy(session, handle_id);
842
                        janus_mutex_lock(&session->mutex);
843
                        g_hash_table_remove(session->ice_handles, &handle_id);
844
                        janus_mutex_unlock(&session->mutex);
845
                        JANUS_LOG(LOG_ERR, "Couldn't attach to plugin '%s', error '%d'\n", plugin_text, error);
846
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_ATTACH, "Couldn't attach to plugin: error '%d'", error);
847
                        goto jsondone;
848
                }
849
                /* Prepare JSON reply */
850
                json_t *reply = json_object();
851
                json_object_set_new(reply, "janus", json_string("success"));
852
                json_object_set_new(reply, "session_id", json_integer(session_id));
853
                json_object_set_new(reply, "transaction", json_string(transaction_text));
854
                json_t *data = json_object();
855
                json_object_set_new(data, "id", json_integer(handle_id));
856
                json_object_set_new(reply, "data", data);
857
                /* Send the success reply */
858
                ret = janus_process_success(request, reply);
859
        } else if(!strcasecmp(message_text, "destroy")) {
860
                if(handle != NULL) {
861
                        /* Query is a session-level command */
862
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
863
                        goto jsondone;
864
                }
865
                /* Schedule the session for deletion */
866
                session->destroy = 1;
867
                janus_mutex_lock(&sessions_mutex);
868
                g_hash_table_remove(sessions, &session->session_id);
869
                g_hash_table_insert(old_sessions, janus_uint64_dup(session->session_id), session);
870
                GSource *timeout_source = g_timeout_source_new_seconds(3);
871
                g_source_set_callback(timeout_source, janus_cleanup_session, session, NULL);
872
                g_source_attach(timeout_source, sessions_watchdog_context);
873
                g_source_unref(timeout_source);
874
                janus_mutex_unlock(&sessions_mutex);
875
                /* Notify the source that the session has been destroyed */
876
                if(session->source && session->source->transport)
877
                        session->source->transport->session_over(session->source->instance, session->session_id, FALSE);
878

    
879
                /* Prepare JSON reply */
880
                json_t *reply = json_object();
881
                json_object_set_new(reply, "janus", json_string("success"));
882
                json_object_set_new(reply, "session_id", json_integer(session_id));
883
                json_object_set_new(reply, "transaction", json_string(transaction_text));
884
                /* Send the success reply */
885
                ret = janus_process_success(request, reply);
886
                /* Notify event handlers as well */
887
                if(janus_events_is_enabled())
888
                        janus_events_notify_handlers(JANUS_EVENT_TYPE_SESSION, session_id, "destroyed", NULL);
889
        } else if(!strcasecmp(message_text, "detach")) {
890
                if(handle == NULL) {
891
                        /* Query is an handle-level command */
892
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
893
                        goto jsondone;
894
                }
895
                if(handle->app == NULL || handle->app_handle == NULL) {
896
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_DETACH, "No plugin to detach from");
897
                        goto jsondone;
898
                }
899
                int error = janus_ice_handle_destroy(session, handle_id);
900
                janus_mutex_lock(&session->mutex);
901
                g_hash_table_remove(session->ice_handles, &handle_id);
902
                janus_mutex_unlock(&session->mutex);
903

    
904
                if(error != 0) {
905
                        /* TODO Make error struct to pass verbose information */
906
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_DETACH, "Couldn't detach from plugin: error '%d'", error);
907
                        /* TODO Delete handle instance */
908
                        goto jsondone;
909
                }
910
                /* Prepare JSON reply */
911
                json_t *reply = json_object();
912
                json_object_set_new(reply, "janus", json_string("success"));
913
                json_object_set_new(reply, "session_id", json_integer(session_id));
914
                json_object_set_new(reply, "transaction", json_string(transaction_text));
915
                /* Send the success reply */
916
                ret = janus_process_success(request, reply);
917
        } else if(!strcasecmp(message_text, "hangup")) {
918
                if(handle == NULL) {
919
                        /* Query is an handle-level command */
920
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
921
                        goto jsondone;
922
                }
923
                if(handle->app == NULL || handle->app_handle == NULL) {
924
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_DETACH, "No plugin attached");
925
                        goto jsondone;
926
                }
927
                janus_ice_webrtc_hangup(handle, "Janus API");
928
                /* Prepare JSON reply */
929
                json_t *reply = json_object();
930
                json_object_set_new(reply, "janus", json_string("success"));
931
                json_object_set_new(reply, "session_id", json_integer(session_id));
932
                json_object_set_new(reply, "transaction", json_string(transaction_text));
933
                /* Send the success reply */
934
                ret = janus_process_success(request, reply);
935
        } else if(!strcasecmp(message_text, "message")) {
936
                if(handle == NULL) {
937
                        /* Query is an handle-level command */
938
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
939
                        goto jsondone;
940
                }
941
                if(handle->app == NULL || handle->app_handle == NULL) {
942
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE, "No plugin to handle this message");
943
                        goto jsondone;
944
                }
945
                janus_plugin *plugin_t = (janus_plugin *)handle->app;
946
                JANUS_LOG(LOG_VERB, "[%"SCNu64"] There's a message for %s\n", handle->handle_id, plugin_t->get_name());
947
                JANUS_VALIDATE_JSON_OBJECT(root, body_parameters,
948
                        error_code, error_cause, FALSE,
949
                        JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
950
                if(error_code != 0) {
951
                        ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
952
                        goto jsondone;
953
                }
954
                json_t *body = json_object_get(root, "body");
955
                /* Is there an SDP attached? */
956
                json_t *jsep = json_object_get(root, "jsep");
957
                char *jsep_type = NULL;
958
                char *jsep_sdp = NULL, *jsep_sdp_stripped = NULL;
959
                if(jsep != NULL) {
960
                        if(!json_is_object(jsep)) {
961
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_JSON_OBJECT, "Invalid jsep object");
962
                                goto jsondone;
963
                        }
964
                        JANUS_VALIDATE_JSON_OBJECT_FORMAT("JSEP error: missing mandatory element (%s)",
965
                                "JSEP error: invalid element type (%s should be %s)",
966
                                jsep, jsep_parameters, error_code, error_cause, FALSE,
967
                                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
968
                        if(error_code != 0) {
969
                                ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
970
                                goto jsondone;
971
                        }
972
                        json_t *type = json_object_get(jsep, "type");
973
                        jsep_type = g_strdup(json_string_value(type));
974
                        type = NULL;
975
                        gboolean do_trickle = TRUE;
976
                        json_t *jsep_trickle = json_object_get(jsep, "trickle");
977
                        do_trickle = jsep_trickle ? json_is_true(jsep_trickle) : TRUE;
978
                        /* Are we still cleaning up from a previous media session? */
979
                        if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_CLEANING)) {
980
                                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Still cleaning up from a previous media session, let's wait a bit...\n", handle->handle_id);
981
                                gint64 waited = 0;
982
                                while(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_CLEANING)) {
983
                                        g_usleep(100000);
984
                                        waited += 100000;
985
                                        if(waited >= 3*G_USEC_PER_SEC) {
986
                                                JANUS_LOG(LOG_VERB, "[%"SCNu64"]   -- Waited 3 seconds, that's enough!\n", handle->handle_id);
987
                                                break;
988
                                        }
989
                                }
990
                        }
991
                        /* Check the JSEP type */
992
                        janus_mutex_lock(&handle->mutex);
993
                        int offer = 0;
994
                        if(!strcasecmp(jsep_type, "offer")) {
995
                                offer = 1;
996
                                janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
997
                                janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_OFFER);
998
                                janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_ANSWER);
999
                        } else if(!strcasecmp(jsep_type, "answer")) {
1000
                                janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_ANSWER);
1001
                                offer = 0;
1002
                        } else {
1003
                                /* TODO Handle other message types as well */
1004
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_JSEP_UNKNOWN_TYPE, "JSEP error: unknown message type '%s'", jsep_type);
1005
                                g_free(jsep_type);
1006
                                janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
1007
                                janus_mutex_unlock(&handle->mutex);
1008
                                goto jsondone;
1009
                        }
1010
                        json_t *sdp = json_object_get(jsep, "sdp");
1011
                        jsep_sdp = (char *)json_string_value(sdp);
1012
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Remote SDP:\n%s", handle->handle_id, jsep_sdp);
1013
                        /* Is this valid SDP? */
1014
                        char error_str[512];
1015
                        int audio = 0, video = 0, data = 0, bundle = 0, rtcpmux = 0, trickle = 0;
1016
                        janus_sdp *parsed_sdp = janus_sdp_preparse(jsep_sdp, error_str, sizeof(error_str), &audio, &video, &data, &bundle, &rtcpmux, &trickle);
1017
                        trickle = trickle && do_trickle;
1018
                        if(parsed_sdp == NULL) {
1019
                                /* Invalid SDP */
1020
                                ret = janus_process_error_string(request, session_id, transaction_text, JANUS_ERROR_JSEP_INVALID_SDP, error_str);
1021
                                g_free(jsep_type);
1022
                                janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
1023
                                janus_mutex_unlock(&handle->mutex);
1024
                                goto jsondone;
1025
                        }
1026
                        /* Notify event handlers */
1027
                        if(janus_events_is_enabled()) {
1028
                                janus_events_notify_handlers(JANUS_EVENT_TYPE_JSEP,
1029
                                        session_id, handle_id, "remote", jsep_type, jsep_sdp);
1030
                        }
1031
                        /* FIXME We're only handling single audio/video lines for now... */
1032
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Audio %s been negotiated, Video %s been negotiated, SCTP/DataChannels %s been negotiated\n",
1033
                                            handle->handle_id,
1034
                                            audio ? "has" : "has NOT",
1035
                                            video ? "has" : "has NOT",
1036
                                            data ? "have" : "have NOT");
1037
                        if(audio > 1) {
1038
                                JANUS_LOG(LOG_WARN, "[%"SCNu64"] More than one audio line? only going to negotiate one...\n", handle->handle_id);
1039
                        }
1040
                        if(video > 1) {
1041
                                JANUS_LOG(LOG_WARN, "[%"SCNu64"] More than one video line? only going to negotiate one...\n", handle->handle_id);
1042
                        }
1043
                        if(data > 1) {
1044
                                JANUS_LOG(LOG_WARN, "[%"SCNu64"] More than one data line? only going to negotiate one...\n", handle->handle_id);
1045
                        }
1046
#ifndef HAVE_SCTP
1047
                        if(data) {
1048
                                JANUS_LOG(LOG_WARN, "[%"SCNu64"]   -- DataChannels have been negotiated, but support for them has not been compiled...\n", handle->handle_id);
1049
                        }
1050
#endif
1051
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"] The browser: %s BUNDLE, %s rtcp-mux, %s doing Trickle ICE\n", handle->handle_id,
1052
                                            bundle  ? "supports" : "does NOT support",
1053
                                            rtcpmux ? "supports" : "does NOT support",
1054
                                            trickle ? "is"       : "is NOT");
1055
                        /* Check if it's a new session, or an update... */
1056
                        if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_READY)
1057
                                        || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT)) {
1058
                                /* New session */
1059
                                if(offer) {
1060
                                        /* Setup ICE locally (we received an offer) */
1061
                                        if(janus_ice_setup_local(handle, offer, audio, video, data, bundle, rtcpmux, trickle) < 0) {
1062
                                                JANUS_LOG(LOG_ERR, "Error setting ICE locally\n");
1063
                                                janus_sdp_free(parsed_sdp);
1064
                                                g_free(jsep_type);
1065
                                                janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
1066
                                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN, "Error setting ICE locally");
1067
                                                janus_mutex_unlock(&handle->mutex);
1068
                                                goto jsondone;
1069
                                        }
1070
                                } else {
1071
                                        /* Make sure we're waiting for an ANSWER in the first place */
1072
                                        if(!handle->agent) {
1073
                                                JANUS_LOG(LOG_ERR, "Unexpected ANSWER (did we offer?)\n");
1074
                                                janus_sdp_free(parsed_sdp);
1075
                                                g_free(jsep_type);
1076
                                                janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
1077
                                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNEXPECTED_ANSWER, "Unexpected ANSWER (did we offer?)");
1078
                                                janus_mutex_unlock(&handle->mutex);
1079
                                                goto jsondone;
1080
                                        }
1081
                                }
1082
                                if(janus_sdp_process(handle, parsed_sdp) < 0) {
1083
                                        JANUS_LOG(LOG_ERR, "Error processing SDP\n");
1084
                                        janus_sdp_free(parsed_sdp);
1085
                                        g_free(jsep_type);
1086
                                        janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
1087
                                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNEXPECTED_ANSWER, "Error processing SDP");
1088
                                        janus_mutex_unlock(&handle->mutex);
1089
                                        goto jsondone;
1090
                                }
1091
                                if(!offer) {
1092
                                        /* Set remote candidates now (we received an answer) */
1093
                                        if(bundle) {
1094
                                                janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE);
1095
                                        } else {
1096
                                                janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE);
1097
                                        }
1098
                                        if(rtcpmux) {
1099
                                                janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_RTCPMUX);
1100
                                        } else {
1101
                                                janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_RTCPMUX);
1102
                                        }
1103
                                        if(trickle) {
1104
                                                janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_TRICKLE);
1105
                                        } else {
1106
                                                janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_TRICKLE);
1107
                                        }
1108
                                        if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)) {
1109
                                                JANUS_LOG(LOG_HUGE, "[%"SCNu64"]   -- bundle is supported by the browser, getting rid of one of the RTP/RTCP components, if any...\n", handle->handle_id);
1110
                                                if(audio) {
1111
                                                        /* Get rid of video and data, if present */
1112
                                                        if(handle->streams && handle->video_stream) {
1113
                                                                handle->audio_stream->video_ssrc = handle->video_stream->video_ssrc;
1114
                                                                handle->audio_stream->video_ssrc_peer = handle->video_stream->video_ssrc_peer;
1115
                                                                handle->audio_stream->video_ssrc_peer_rtx = handle->video_stream->video_ssrc_peer_rtx;
1116
                                                                nice_agent_attach_recv(handle->agent, handle->video_stream->stream_id, 1, g_main_loop_get_context (handle->iceloop), NULL, NULL);
1117
                                                                if(!janus_ice_is_rtcpmux_forced())
1118
                                                                        nice_agent_attach_recv(handle->agent, handle->video_stream->stream_id, 2, g_main_loop_get_context (handle->iceloop), NULL, NULL);
1119
                                                                nice_agent_remove_stream(handle->agent, handle->video_stream->stream_id);
1120
                                                                janus_ice_stream_free(handle->streams, handle->video_stream);
1121
                                                        }
1122
                                                        handle->video_stream = NULL;
1123
                                                        handle->video_id = 0;
1124
                                                        if(handle->streams && handle->data_stream) {
1125
                                                                nice_agent_attach_recv(handle->agent, handle->data_stream->stream_id, 1, g_main_loop_get_context (handle->iceloop), NULL, NULL);
1126
                                                                nice_agent_remove_stream(handle->agent, handle->data_stream->stream_id);
1127
                                                                janus_ice_stream_free(handle->streams, handle->data_stream);
1128
                                                        }
1129
                                                        handle->data_stream = NULL;
1130
                                                        handle->data_id = 0;
1131
                                                        if(!video) {
1132
                                                                handle->audio_stream->video_ssrc = 0;
1133
                                                                handle->audio_stream->video_ssrc_peer = 0;
1134
                                                                g_free(handle->audio_stream->video_rtcp_ctx);
1135
                                                                handle->audio_stream->video_rtcp_ctx = NULL;
1136
                                                        }
1137
                                                } else if(video) {
1138
                                                        /* Get rid of data, if present */
1139
                                                        if(handle->streams && handle->data_stream) {
1140
                                                                nice_agent_attach_recv(handle->agent, handle->data_stream->stream_id, 1, g_main_loop_get_context (handle->iceloop), NULL, NULL);
1141
                                                                nice_agent_remove_stream(handle->agent, handle->data_stream->stream_id);
1142
                                                                janus_ice_stream_free(handle->streams, handle->data_stream);
1143
                                                        }
1144
                                                        handle->data_stream = NULL;
1145
                                                        handle->data_id = 0;
1146
                                                }
1147
                                        }
1148
                                        if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_RTCPMUX) && !janus_ice_is_rtcpmux_forced()) {
1149
                                                JANUS_LOG(LOG_HUGE, "[%"SCNu64"]   -- rtcp-mux is supported by the browser, getting rid of RTCP components, if any...\n", handle->handle_id);
1150
                                                if(handle->audio_stream && handle->audio_stream->components != NULL) {
1151
                                                        nice_agent_attach_recv(handle->agent, handle->audio_id, 2, g_main_loop_get_context (handle->iceloop), NULL, NULL);
1152
                                                        /* Free the component */
1153
                                                        janus_ice_component_free(handle->audio_stream->components, handle->audio_stream->rtcp_component);
1154
                                                        handle->audio_stream->rtcp_component = NULL;
1155
                                                        /* Create a dummy candidate and enforce it as the one to use for this now unneeded component */
1156
                                                        NiceCandidate *c = nice_candidate_new(NICE_CANDIDATE_TYPE_HOST);
1157
                                                        c->component_id = 2;
1158
                                                        c->stream_id = handle->audio_stream->stream_id;
1159
#ifndef HAVE_LIBNICE_TCP
1160
                                                        c->transport = NICE_CANDIDATE_TRANSPORT_UDP;
1161
#endif
1162
                                                        strncpy(c->foundation, "1", NICE_CANDIDATE_MAX_FOUNDATION);
1163
                                                        c->priority = 1;
1164
                                                        nice_address_set_from_string(&c->addr, "127.0.0.1");
1165
                                                        nice_address_set_port(&c->addr, janus_ice_get_rtcpmux_blackhole_port());
1166
                                                        c->username = g_strdup(handle->audio_stream->ruser);
1167
                                                        c->password = g_strdup(handle->audio_stream->rpass);
1168
                                                        if(!nice_agent_set_selected_remote_candidate(handle->agent, handle->audio_stream->stream_id, 2, c)) {
1169
                                                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Error forcing dummy candidate on RTCP component of stream %d\n", handle->handle_id, handle->audio_stream->stream_id);
1170
                                                                nice_candidate_free(c);
1171
                                                        }
1172
                                                }
1173
                                                if(handle->video_stream && handle->video_stream->components != NULL) {
1174
                                                        nice_agent_attach_recv(handle->agent, handle->video_id, 2, g_main_loop_get_context (handle->iceloop), NULL, NULL);
1175
                                                        /* Free the component */
1176
                                                        janus_ice_component_free(handle->video_stream->components, handle->video_stream->rtcp_component);
1177
                                                        handle->video_stream->rtcp_component = NULL;
1178
                                                        /* Create a dummy candidate and enforce it as the one to use for this now unneeded component */
1179
                                                        NiceCandidate *c = nice_candidate_new(NICE_CANDIDATE_TYPE_HOST);
1180
                                                        c->component_id = 2;
1181
                                                        c->stream_id = handle->video_stream->stream_id;
1182
#ifndef HAVE_LIBNICE_TCP
1183
                                                        c->transport = NICE_CANDIDATE_TRANSPORT_UDP;
1184
#endif
1185
                                                        strncpy(c->foundation, "1", NICE_CANDIDATE_MAX_FOUNDATION);
1186
                                                        c->priority = 1;
1187
                                                        nice_address_set_from_string(&c->addr, "127.0.0.1");
1188
                                                        nice_address_set_port(&c->addr, janus_ice_get_rtcpmux_blackhole_port());
1189
                                                        c->username = g_strdup(handle->video_stream->ruser);
1190
                                                        c->password = g_strdup(handle->video_stream->rpass);
1191
                                                        if(!nice_agent_set_selected_remote_candidate(handle->agent, handle->video_stream->stream_id, 2, c)) {
1192
                                                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Error forcing dummy candidate on RTCP component of stream %d\n", handle->handle_id, handle->video_stream->stream_id);
1193
                                                                nice_candidate_free(c);
1194
                                                        }
1195
                                                }
1196
                                        }
1197
                                        /* FIXME Any disabled m-line? */
1198
                                        if(strstr(jsep_sdp, "m=audio 0")) {
1199
                                                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Audio disabled via SDP\n", handle->handle_id);
1200
                                                if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)
1201
                                                                || (!video && !data)) {
1202
                                                        JANUS_LOG(LOG_HUGE, "  -- Marking audio stream as disabled\n");
1203
                                                        janus_ice_stream *stream = g_hash_table_lookup(handle->streams, GUINT_TO_POINTER(handle->audio_id));
1204
                                                        if(stream)
1205
                                                                stream->disabled = TRUE;
1206
                                                }
1207
                                        }
1208
                                        if(strstr(jsep_sdp, "m=video 0")) {
1209
                                                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Video disabled via SDP\n", handle->handle_id);
1210
                                                if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)
1211
                                                                || (!audio && !data)) {
1212
                                                        JANUS_LOG(LOG_HUGE, "  -- Marking video stream as disabled\n");
1213
                                                        janus_ice_stream *stream = NULL;
1214
                                                        if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)) {
1215
                                                                stream = g_hash_table_lookup(handle->streams, GUINT_TO_POINTER(handle->video_id));
1216
                                                        } else {
1217
                                                                gint id = handle->audio_id > 0 ? handle->audio_id : handle->video_id;
1218
                                                                stream = g_hash_table_lookup(handle->streams, GUINT_TO_POINTER(id));
1219
                                                        }
1220
                                                        if(stream)
1221
                                                                stream->disabled = TRUE;
1222
                                                }
1223
                                        }
1224
                                        if(strstr(jsep_sdp, "m=application 0 DTLS/SCTP")) {
1225
                                                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Data Channel disabled via SDP\n", handle->handle_id);
1226
                                                if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)
1227
                                                                || (!audio && !video)) {
1228
                                                        JANUS_LOG(LOG_HUGE, "  -- Marking data channel stream as disabled\n");
1229
                                                        janus_ice_stream *stream = NULL;
1230
                                                        if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)) {
1231
                                                                stream = g_hash_table_lookup(handle->streams, GUINT_TO_POINTER(handle->data_id));
1232
                                                        } else {
1233
                                                                gint id = handle->audio_id > 0 ? handle->audio_id : (handle->video_id > 0 ? handle->video_id : handle->data_id);
1234
                                                                stream = g_hash_table_lookup(handle->streams, GUINT_TO_POINTER(id));
1235
                                                        }
1236
                                                        if(stream)
1237
                                                                stream->disabled = TRUE;
1238
                                                }
1239
                                        }
1240
                                        /* We got our answer */
1241
                                        janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
1242
                                        /* Any pending trickles? */
1243
                                        if(handle->pending_trickles) {
1244
                                                JANUS_LOG(LOG_VERB, "[%"SCNu64"]   -- Processing %d pending trickle candidates\n", handle->handle_id, g_list_length(handle->pending_trickles));
1245
                                                GList *temp = NULL;
1246
                                                while(handle->pending_trickles) {
1247
                                                        temp = g_list_first(handle->pending_trickles);
1248
                                                        handle->pending_trickles = g_list_remove_link(handle->pending_trickles, temp);
1249
                                                        janus_ice_trickle *trickle = (janus_ice_trickle *)temp->data;
1250
                                                        g_list_free(temp);
1251
                                                        if(trickle == NULL)
1252
                                                                continue;
1253
                                                        if((janus_get_monotonic_time() - trickle->received) > 45*G_USEC_PER_SEC) {
1254
                                                                /* FIXME Candidate is too old, discard it */
1255
                                                                janus_ice_trickle_destroy(trickle);
1256
                                                                /* FIXME We should report that */
1257
                                                                continue;
1258
                                                        }
1259
                                                        json_t *candidate = trickle->candidate;
1260
                                                        if(candidate == NULL) {
1261
                                                                janus_ice_trickle_destroy(trickle);
1262
                                                                continue;
1263
                                                        }
1264
                                                        if(json_is_object(candidate)) {
1265
                                                                /* We got a single candidate */
1266
                                                                int error = 0;
1267
                                                                const char *error_string = NULL;
1268
                                                                if((error = janus_ice_trickle_parse(handle, candidate, &error_string)) != 0) {
1269
                                                                        /* FIXME We should report the error parsing the trickle candidate */
1270
                                                                }
1271
                                                        } else if(json_is_array(candidate)) {
1272
                                                                /* We got multiple candidates in an array */
1273
                                                                JANUS_LOG(LOG_VERB, "Got multiple candidates (%zu)\n", json_array_size(candidate));
1274
                                                                if(json_array_size(candidate) > 0) {
1275
                                                                        /* Handle remote candidates */
1276
                                                                        size_t i = 0;
1277
                                                                        for(i=0; i<json_array_size(candidate); i++) {
1278
                                                                                json_t *c = json_array_get(candidate, i);
1279
                                                                                /* FIXME We don't care if any trickle fails to parse */
1280
                                                                                janus_ice_trickle_parse(handle, c, NULL);
1281
                                                                        }
1282
                                                                }
1283
                                                        }
1284
                                                        /* Done, free candidate */
1285
                                                        janus_ice_trickle_destroy(trickle);
1286
                                                }
1287
                                        }
1288
                                        /* This was an answer, check if it's time to start ICE */
1289
                                        if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_TRICKLE) &&
1290
                                                        !janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALL_TRICKLES)) {
1291
                                                JANUS_LOG(LOG_VERB, "[%"SCNu64"]   -- ICE Trickling is supported by the browser, waiting for remote candidates...\n", handle->handle_id);
1292
                                                janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_START);
1293
                                        } else {
1294
                                                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Done! Sending connectivity checks...\n", handle->handle_id);
1295
                                                if(handle->audio_id > 0) {
1296
                                                        janus_ice_setup_remote_candidates(handle, handle->audio_id, 1);
1297
                                                        if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_RTCPMUX))        /* http://tools.ietf.org/html/rfc5761#section-5.1.3 */
1298
                                                                janus_ice_setup_remote_candidates(handle, handle->audio_id, 2);
1299
                                                }
1300
                                                if(handle->video_id > 0) {
1301
                                                        janus_ice_setup_remote_candidates(handle, handle->video_id, 1);
1302
                                                        if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_RTCPMUX))        /* http://tools.ietf.org/html/rfc5761#section-5.1.3 */
1303
                                                                janus_ice_setup_remote_candidates(handle, handle->video_id, 2);
1304
                                                }
1305
                                                if(handle->data_id > 0) {
1306
                                                        janus_ice_setup_remote_candidates(handle, handle->data_id, 1);
1307
                                                }
1308
                                        }
1309
                                }
1310
                        } else {
1311
                                /* TODO Actually handle session updates: for now we ignore them, and just relay them to plugins */
1312
                                JANUS_LOG(LOG_WARN, "[%"SCNu64"] Ignoring negotiation update, we don't support them yet...\n", handle->handle_id);
1313
                        }
1314
                        handle->remote_sdp = g_strdup(jsep_sdp);
1315
                        janus_mutex_unlock(&handle->mutex);
1316
                        /* Anonymize SDP */
1317
                        if(janus_sdp_anonymize(parsed_sdp) < 0) {
1318
                                /* Invalid SDP */
1319
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_JSEP_INVALID_SDP, "JSEP error: invalid SDP");
1320
                                janus_sdp_free(parsed_sdp);
1321
                                g_free(jsep_type);
1322
                                janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
1323
                                goto jsondone;
1324
                        }
1325
                        jsep_sdp_stripped = janus_sdp_write(parsed_sdp);
1326
                        janus_sdp_free(parsed_sdp);
1327
                        sdp = NULL;
1328
                        janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
1329
                }
1330

    
1331
                /* Make sure the app handle is still valid */
1332
                if(handle->app == NULL || handle->app_handle == NULL || !janus_plugin_session_is_alive(handle->app_handle)) {
1333
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE, "No plugin to handle this message");
1334
                        g_free(jsep_type);
1335
                        g_free(jsep_sdp_stripped);
1336
                        janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
1337
                        goto jsondone;
1338
                }
1339

    
1340
                /* Send the message to the plugin (which must eventually free transaction_text and unref the two objects, body and jsep) */
1341
                json_incref(body);
1342
                janus_plugin_result *result = plugin_t->handle_message(handle->app_handle,
1343
                        g_strdup((char *)transaction_text), body,
1344
                        jsep_sdp_stripped ? json_pack("{ssss}", "type", jsep_type, "sdp", jsep_sdp_stripped) : NULL);
1345
                g_free(jsep_type);
1346
                g_free(jsep_sdp_stripped);
1347
                if(result == NULL) {
1348
                        /* Something went horribly wrong! */
1349
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE, "Plugin didn't give a result");
1350
                        goto jsondone;
1351
                }
1352
                if(result->type == JANUS_PLUGIN_OK) {
1353
                        /* The plugin gave a result already (synchronous request/response) */
1354
                        if(result->content == NULL || !json_is_object(result->content)) {
1355
                                /* Missing content, or not a JSON object */
1356
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE,
1357
                                        result->content == NULL ?
1358
                                                "Plugin didn't provide any content for this synchronous response" :
1359
                                                "Plugin returned an invalid JSON response");
1360
                                janus_plugin_result_destroy(result);
1361
                                goto jsondone;
1362
                        }
1363
                        /* Reference the content, as destroying the result instance will decref it */
1364
                        json_incref(result->content);
1365
                        /* Prepare JSON response */
1366
                        json_t *reply = json_object();
1367
                        json_object_set_new(reply, "janus", json_string("success"));
1368
                        json_object_set_new(reply, "session_id", json_integer(session->session_id));
1369
                        json_object_set_new(reply, "sender", json_integer(handle->handle_id));
1370
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1371
                        json_t *plugin_data = json_object();
1372
                        json_object_set_new(plugin_data, "plugin", json_string(plugin_t->get_package()));
1373
                        json_object_set_new(plugin_data, "data", result->content);
1374
                        json_object_set_new(reply, "plugindata", plugin_data);
1375
                        /* Send the success reply */
1376
                        ret = janus_process_success(request, reply);
1377
                } else if(result->type == JANUS_PLUGIN_OK_WAIT) {
1378
                        /* The plugin received the request but didn't process it yet, send an ack (asynchronous notifications may follow) */
1379
                        json_t *reply = json_object();
1380
                        json_object_set_new(reply, "janus", json_string("ack"));
1381
                        json_object_set_new(reply, "session_id", json_integer(session_id));
1382
                        if(result->text)
1383
                                json_object_set_new(reply, "hint", json_string(result->text));
1384
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1385
                        /* Send the success reply */
1386
                        ret = janus_process_success(request, reply);
1387
                } else {
1388
                        /* Something went horribly wrong! */
1389
                        ret = janus_process_error_string(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE,
1390
                                (char *)(result->text ? result->text : "Plugin returned a severe (unknown) error"));
1391
                        janus_plugin_result_destroy(result);
1392
                        goto jsondone;
1393
                }
1394
                janus_plugin_result_destroy(result);
1395
        } else if(!strcasecmp(message_text, "trickle")) {
1396
                if(handle == NULL) {
1397
                        /* Trickle is an handle-level command */
1398
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
1399
                        goto jsondone;
1400
                }
1401
                if(handle->app == NULL || handle->app_handle == NULL || !janus_plugin_session_is_alive(handle->app_handle)) {
1402
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE, "No plugin to handle this trickle candidate");
1403
                        goto jsondone;
1404
                }
1405
                json_t *candidate = json_object_get(root, "candidate");
1406
                json_t *candidates = json_object_get(root, "candidates");
1407
                if(candidate == NULL && candidates == NULL) {
1408
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_MISSING_MANDATORY_ELEMENT, "Missing mandatory element (candidate|candidates)");
1409
                        goto jsondone;
1410
                }
1411
                if(candidate != NULL && candidates != NULL) {
1412
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_JSON, "Can't have both candidate and candidates");
1413
                        goto jsondone;
1414
                }
1415
                janus_mutex_lock(&handle->mutex);
1416
                if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_TRICKLE)) {
1417
                        /* It looks like this peer supports Trickle, after all */
1418
                        JANUS_LOG(LOG_VERB, "Handle %"SCNu64" supports trickle even if it didn't negotiate it...\n", handle->handle_id);
1419
                        janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_TRICKLE);
1420
                }
1421
                /* Is there any stream ready? this trickle may get here before the SDP it relates to */
1422
                if(handle->audio_stream == NULL && handle->video_stream == NULL && handle->data_stream == NULL) {
1423
                        JANUS_LOG(LOG_WARN, "[%"SCNu64"] No stream, queueing this trickle as it got here before the SDP...\n", handle->handle_id);
1424
                        /* Enqueue this trickle candidate(s), we'll process this later */
1425
                        janus_ice_trickle *early_trickle = janus_ice_trickle_new(handle, transaction_text, candidate ? candidate : candidates);
1426
                        handle->pending_trickles = g_list_append(handle->pending_trickles, early_trickle);
1427
                        /* Send the ack right away, an event will tell the application if the candidate(s) failed */
1428
                        goto trickledone;
1429
                }
1430
                /* Is the ICE stack ready already? */
1431
                if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER) ||
1432
                                !janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_OFFER) ||
1433
                                !janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_ANSWER)) {
1434
                        const char *cause = NULL;
1435
                        if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER))
1436
                                cause = "processing the offer";
1437
                        else if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_ANSWER))
1438
                                cause = "waiting for the answer";
1439
                        else if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_OFFER))
1440
                                cause = "waiting for the offer";
1441
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Still %s, queueing this trickle to wait until we're done there...\n",
1442
                                handle->handle_id, cause);
1443
                        /* Enqueue this trickle candidate(s), we'll process this later */
1444
                        janus_ice_trickle *early_trickle = janus_ice_trickle_new(handle, transaction_text, candidate ? candidate : candidates);
1445
                        handle->pending_trickles = g_list_append(handle->pending_trickles, early_trickle);
1446
                        /* Send the ack right away, an event will tell the application if the candidate(s) failed */
1447
                        goto trickledone;
1448
                }
1449
                if(candidate != NULL) {
1450
                        /* We got a single candidate */
1451
                        int error = 0;
1452
                        const char *error_string = NULL;
1453
                        if((error = janus_ice_trickle_parse(handle, candidate, &error_string)) != 0) {
1454
                                ret = janus_process_error(request, session_id, transaction_text, error, "%s", error_string);
1455
                                janus_mutex_unlock(&handle->mutex);
1456
                                goto jsondone;
1457
                        }
1458
                } else {
1459
                        /* We got multiple candidates in an array */
1460
                        if(!json_is_array(candidates)) {
1461
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_ELEMENT_TYPE, "candidates is not an array");
1462
                                janus_mutex_unlock(&handle->mutex);
1463
                                goto jsondone;
1464
                        }
1465
                        JANUS_LOG(LOG_VERB, "Got multiple candidates (%zu)\n", json_array_size(candidates));
1466
                        if(json_array_size(candidates) > 0) {
1467
                                /* Handle remote candidates */
1468
                                size_t i = 0;
1469
                                for(i=0; i<json_array_size(candidates); i++) {
1470
                                        json_t *c = json_array_get(candidates, i);
1471
                                        /* FIXME We don't care if any trickle fails to parse */
1472
                                        janus_ice_trickle_parse(handle, c, NULL);
1473
                                }
1474
                        }
1475
                }
1476

    
1477
trickledone:
1478
                janus_mutex_unlock(&handle->mutex);
1479
                /* We reply right away, not to block the web server... */
1480
                json_t *reply = json_object();
1481
                json_object_set_new(reply, "janus", json_string("ack"));
1482
                json_object_set_new(reply, "session_id", json_integer(session_id));
1483
                json_object_set_new(reply, "transaction", json_string(transaction_text));
1484
                /* Send the success reply */
1485
                ret = janus_process_success(request, reply);
1486
        } else {
1487
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN_REQUEST, "Unknown request '%s'", message_text);
1488
        }
1489

    
1490
jsondone:
1491
        /* Done processing */
1492
        return ret;
1493
}
1494

    
1495
/* Admin/monitor WebServer requests handler */
1496
int janus_process_incoming_admin_request(janus_request *request) {
1497
        int ret = -1;
1498
        int error_code = 0;
1499
        char error_cause[100];
1500
        if(request == NULL) {
1501
                JANUS_LOG(LOG_ERR, "Missing request or payload to process, giving up...\n");
1502
                return ret;
1503
        }
1504
        json_t *root = request->message;
1505
        /* Ok, let's start with the ids */
1506
        guint64 session_id = 0, handle_id = 0;
1507
        json_t *s = json_object_get(root, "session_id");
1508
        if(s && json_is_integer(s))
1509
                session_id = json_integer_value(s);
1510
        json_t *h = json_object_get(root, "handle_id");
1511
        if(h && json_is_integer(h))
1512
                handle_id = json_integer_value(h);
1513

    
1514
        /* Get transaction and message request */
1515
        JANUS_VALIDATE_JSON_OBJECT(root, admin_parameters,
1516
                error_code, error_cause, FALSE,
1517
                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
1518
        if(error_code != 0) {
1519
                ret = janus_process_error_string(request, session_id, NULL, error_code, error_cause);
1520
                goto jsondone;
1521
        }
1522
        json_t *transaction = json_object_get(root, "transaction");
1523
        const gchar *transaction_text = json_string_value(transaction);
1524
        json_t *message = json_object_get(root, "janus");
1525
        if(!message) {
1526
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_MISSING_MANDATORY_ELEMENT, "Missing mandatory element (janus)");
1527
                goto jsondone;
1528
        }
1529
        if(!json_is_string(message)) {
1530
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_ELEMENT_TYPE, "Invalid element type (janus should be a string)");
1531
                goto jsondone;
1532
        }
1533
        const gchar *message_text = json_string_value(message);
1534

    
1535
        if(session_id == 0 && handle_id == 0) {
1536
                /* Can only be a 'Get all sessions' or some general setting manipulation request */
1537
                if(!strcasecmp(message_text, "info")) {
1538
                        /* The generic info request */
1539
                        ret = janus_process_success(request, janus_info(transaction_text));
1540
                        goto jsondone;
1541
                }
1542
                if(admin_api_secret != NULL) {
1543
                        /* There's an admin/monitor secret, check that the client provided it */
1544
                        json_t *secret = json_object_get(root, "admin_secret");
1545
                        if(!secret || !json_is_string(secret) || !janus_strcmp_const_time(json_string_value(secret), admin_api_secret)) {
1546
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNAUTHORIZED, NULL);
1547
                                goto jsondone;
1548
                        }
1549
                }
1550
                if(!strcasecmp(message_text, "get_status")) {
1551
                        /* Return some info on the settings (mostly debug-related, at the moment) */
1552
                        json_t *reply = json_object();
1553
                        json_object_set_new(reply, "janus", json_string("success"));
1554
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1555
                        json_t *status = json_object();
1556
                        json_object_set_new(status, "token_auth", janus_auth_is_enabled() ? json_true() : json_false());
1557
                        json_object_set_new(status, "session_timeout", json_integer(session_timeout));
1558
                        json_object_set_new(status, "log_level", json_integer(janus_log_level));
1559
                        json_object_set_new(status, "log_timestamps", janus_log_timestamps ? json_true() : json_false());
1560
                        json_object_set_new(status, "log_colors", janus_log_colors ? json_true() : json_false());
1561
                        json_object_set_new(status, "locking_debug", lock_debug ? json_true() : json_false());
1562
                        json_object_set_new(status, "libnice_debug", janus_ice_is_ice_debugging_enabled() ? json_true() : json_false());
1563
                        json_object_set_new(status, "max_nack_queue", json_integer(janus_get_max_nack_queue()));
1564
                        json_object_set_new(status, "no_media_timer", json_integer(janus_get_no_media_timer()));
1565
                        json_object_set_new(reply, "status", status);
1566
                        /* Send the success reply */
1567
                        ret = janus_process_success(request, reply);
1568
                        goto jsondone;
1569
                } else if(!strcasecmp(message_text, "set_session_timeout")) {
1570
                        /* Change the session timeout value */
1571
                        JANUS_VALIDATE_JSON_OBJECT(root, timeout_parameters,
1572
                                error_code, error_cause, FALSE,
1573
                                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
1574
                        if(error_code != 0) {
1575
                                ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
1576
                                goto jsondone;
1577
                        }
1578
                        json_t *timeout = json_object_get(root, "timeout");
1579
                        int timeout_num = json_integer_value(timeout);
1580
                        if(timeout_num < 0) {
1581
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_ELEMENT_TYPE, "Invalid element type (timeout should be a positive integer)");
1582
                                goto jsondone;
1583
                        }
1584
                        session_timeout = timeout_num;
1585
                        /* Prepare JSON reply */
1586
                        json_t *reply = json_object();
1587
                        json_object_set_new(reply, "janus", json_string("success"));
1588
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1589
                        json_object_set_new(reply, "timeout", json_integer(session_timeout));
1590
                        /* Send the success reply */
1591
                        ret = janus_process_success(request, reply);
1592
                        goto jsondone;
1593
                } else if(!strcasecmp(message_text, "set_log_level")) {
1594
                        /* Change the debug logging level */
1595
                        JANUS_VALIDATE_JSON_OBJECT(root, level_parameters,
1596
                                error_code, error_cause, FALSE,
1597
                                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
1598
                        if(error_code != 0) {
1599
                                ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
1600
                                goto jsondone;
1601
                        }
1602
                        json_t *level = json_object_get(root, "level");
1603
                        int level_num = json_integer_value(level);
1604
                        if(level_num < LOG_NONE || level_num > LOG_MAX) {
1605
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_ELEMENT_TYPE, "Invalid element type (level should be between %d and %d)", LOG_NONE, LOG_MAX);
1606
                                goto jsondone;
1607
                        }
1608
                        janus_log_level = level_num;
1609
                        /* Prepare JSON reply */
1610
                        json_t *reply = json_object();
1611
                        json_object_set_new(reply, "janus", json_string("success"));
1612
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1613
                        json_object_set_new(reply, "level", json_integer(janus_log_level));
1614
                        /* Send the success reply */
1615
                        ret = janus_process_success(request, reply);
1616
                        goto jsondone;
1617
                } else if(!strcasecmp(message_text, "set_locking_debug")) {
1618
                        /* Enable/disable the locking debug (would show a message on the console for every lock attempt) */
1619
                        JANUS_VALIDATE_JSON_OBJECT(root, debug_parameters,
1620
                                error_code, error_cause, FALSE,
1621
                                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
1622
                        if(error_code != 0) {
1623
                                ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
1624
                                goto jsondone;
1625
                        }
1626
                        json_t *debug = json_object_get(root, "debug");
1627
                        lock_debug = json_is_true(debug);
1628
                        /* Prepare JSON reply */
1629
                        json_t *reply = json_object();
1630
                        json_object_set_new(reply, "janus", json_string("success"));
1631
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1632
                        json_object_set_new(reply, "locking_debug", lock_debug ? json_true() : json_false());
1633
                        /* Send the success reply */
1634
                        ret = janus_process_success(request, reply);
1635
                        goto jsondone;
1636
                } else if(!strcasecmp(message_text, "set_log_timestamps")) {
1637
                        /* Enable/disable the log timestamps */
1638
                        JANUS_VALIDATE_JSON_OBJECT(root, timestamps_parameters,
1639
                                error_code, error_cause, FALSE,
1640
                                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
1641
                        if(error_code != 0) {
1642
                                ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
1643
                                goto jsondone;
1644
                        }
1645
                        json_t *timestamps = json_object_get(root, "timestamps");
1646
                        janus_log_timestamps = json_is_true(timestamps);
1647
                        /* Prepare JSON reply */
1648
                        json_t *reply = json_object();
1649
                        json_object_set_new(reply, "janus", json_string("success"));
1650
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1651
                        json_object_set_new(reply, "log_timestamps", janus_log_timestamps ? json_true() : json_false());
1652
                        /* Send the success reply */
1653
                        ret = janus_process_success(request, reply);
1654
                        goto jsondone;
1655
                } else if(!strcasecmp(message_text, "set_log_colors")) {
1656
                        /* Enable/disable the log colors */
1657
                        JANUS_VALIDATE_JSON_OBJECT(root, colors_parameters,
1658
                                error_code, error_cause, FALSE,
1659
                                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
1660
                        if(error_code != 0) {
1661
                                ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
1662
                                goto jsondone;
1663
                        }
1664
                        json_t *colors = json_object_get(root, "colors");
1665
                        janus_log_colors = json_is_true(colors);
1666
                        /* Prepare JSON reply */
1667
                        json_t *reply = json_object();
1668
                        json_object_set_new(reply, "janus", json_string("success"));
1669
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1670
                        json_object_set_new(reply, "log_colors", janus_log_colors ? json_true() : json_false());
1671
                        /* Send the success reply */
1672
                        ret = janus_process_success(request, reply);
1673
                        goto jsondone;
1674
                } else if(!strcasecmp(message_text, "set_libnice_debug")) {
1675
                        /* Enable/disable the libnice debugging (http://nice.freedesktop.org/libnice/libnice-Debug-messages.html) */
1676
                        JANUS_VALIDATE_JSON_OBJECT(root, debug_parameters,
1677
                                error_code, error_cause, FALSE,
1678
                                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
1679
                        if(error_code != 0) {
1680
                                ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
1681
                                goto jsondone;
1682
                        }
1683
                        json_t *debug = json_object_get(root, "debug");
1684
                        if(json_is_true(debug)) {
1685
                                janus_ice_debugging_enable();
1686
                        } else {
1687
                                janus_ice_debugging_disable();
1688
                        }
1689
                        /* Prepare JSON reply */
1690
                        json_t *reply = json_object();
1691
                        json_object_set_new(reply, "janus", json_string("success"));
1692
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1693
                        json_object_set_new(reply, "libnice_debug", janus_ice_is_ice_debugging_enabled() ? json_true() : json_false());
1694
                        /* Send the success reply */
1695
                        ret = janus_process_success(request, reply);
1696
                        goto jsondone;
1697
                } else if(!strcasecmp(message_text, "set_max_nack_queue")) {
1698
                        /* Change the current value for the max NACK queue */
1699
                        JANUS_VALIDATE_JSON_OBJECT(root, mnq_parameters,
1700
                                error_code, error_cause, FALSE,
1701
                                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
1702
                        if(error_code != 0) {
1703
                                ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
1704
                                goto jsondone;
1705
                        }
1706
                        json_t *mnq = json_object_get(root, "max_nack_queue");
1707
                        int mnq_num = json_integer_value(mnq);
1708
                        if(mnq_num < 0 || (mnq_num > 0 && mnq_num < 200)) {
1709
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_ELEMENT_TYPE, "Invalid element type (max_nack_queue, if provided, should be greater than 200)");
1710
                                goto jsondone;
1711
                        }
1712
                        janus_set_max_nack_queue(mnq_num);
1713
                        /* Prepare JSON reply */
1714
                        json_t *reply = json_object();
1715
                        json_object_set_new(reply, "janus", json_string("success"));
1716
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1717
                        json_object_set_new(reply, "max_nack_queue", json_integer(janus_get_max_nack_queue()));
1718
                        /* Send the success reply */
1719
                        ret = janus_process_success(request, reply);
1720
                        goto jsondone;
1721
                } else if(!strcasecmp(message_text, "set_no_media_timer")) {
1722
                        /* Change the current value for the no-media timer */
1723
                        JANUS_VALIDATE_JSON_OBJECT(root, nmt_parameters,
1724
                                error_code, error_cause, FALSE,
1725
                                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
1726
                        if(error_code != 0) {
1727
                                ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
1728
                                goto jsondone;
1729
                        }
1730
                        json_t *nmt = json_object_get(root, "no_media_timer");
1731
                        int nmt_num = json_integer_value(nmt);
1732
                        janus_set_no_media_timer(nmt_num);
1733
                        /* Prepare JSON reply */
1734
                        json_t *reply = json_object();
1735
                        json_object_set_new(reply, "janus", json_string("success"));
1736
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1737
                        json_object_set_new(reply, "no_media_timer", json_integer(janus_get_no_media_timer()));
1738
                        /* Send the success reply */
1739
                        ret = janus_process_success(request, reply);
1740
                        goto jsondone;
1741
                } else if(!strcasecmp(message_text, "list_sessions")) {
1742
                        /* List sessions */
1743
                        session_id = 0;
1744
                        json_t *list = json_array();
1745
                        if(sessions != NULL && g_hash_table_size(sessions) > 0) {
1746
                                janus_mutex_lock(&sessions_mutex);
1747
                                GHashTableIter iter;
1748
                                gpointer value;
1749
                                g_hash_table_iter_init(&iter, sessions);
1750
                                while (g_hash_table_iter_next(&iter, NULL, &value)) {
1751
                                        janus_session *session = value;
1752
                                        if(session == NULL) {
1753
                                                continue;
1754
                                        }
1755
                                        json_array_append_new(list, json_integer(session->session_id));
1756
                                }
1757
                                janus_mutex_unlock(&sessions_mutex);
1758
                        }
1759
                        /* Prepare JSON reply */
1760
                        json_t *reply = json_object();
1761
                        json_object_set_new(reply, "janus", json_string("success"));
1762
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1763
                        json_object_set_new(reply, "sessions", list);
1764
                        /* Send the success reply */
1765
                        ret = janus_process_success(request, reply);
1766
                        goto jsondone;
1767
                } else if(!strcasecmp(message_text, "add_token")) {
1768
                        /* Add a token valid for authentication */
1769
                        if(!janus_auth_is_enabled()) {
1770
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN, "Token based authentication disabled");
1771
                                goto jsondone;
1772
                        }
1773
                        JANUS_VALIDATE_JSON_OBJECT(root, add_token_parameters,
1774
                                error_code, error_cause, FALSE,
1775
                                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
1776
                        if(error_code != 0) {
1777
                                ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
1778
                                goto jsondone;
1779
                        }
1780
                        json_t *token = json_object_get(root, "token");
1781
                        const char *token_value = json_string_value(token);
1782
                        /* Any plugin this token should be limited to? */
1783
                        json_t *allowed = json_object_get(root, "plugins");
1784
                        /* First of all, add the new token */
1785
                        if(!janus_auth_add_token(token_value)) {
1786
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN, "Error adding token");
1787
                                goto jsondone;
1788
                        }
1789
                        /* Then take care of the plugins access limitations, if any */
1790
                        if(allowed && json_array_size(allowed) > 0) {
1791
                                /* Specify which plugins this token has access to */
1792
                                size_t i = 0;
1793
                                for(i=0; i<json_array_size(allowed); i++) {
1794
                                        json_t *p = json_array_get(allowed, i);
1795
                                        if(!p || !json_is_string(p)) {
1796
                                                /* FIXME Should we fail here? */
1797
                                                JANUS_LOG(LOG_WARN, "Invalid plugin passed to the new token request, skipping...\n");
1798
                                                continue;
1799
                                        }
1800
                                        const gchar *plugin_text = json_string_value(p);
1801
                                        janus_plugin *plugin_t = janus_plugin_find(plugin_text);
1802
                                        if(plugin_t == NULL) {
1803
                                                /* FIXME Should we fail here? */
1804
                                                JANUS_LOG(LOG_WARN, "No such plugin '%s' passed to the new token request, skipping...\n", plugin_text);
1805
                                                continue;
1806
                                        }
1807
                                        if(!janus_auth_allow_plugin(token_value, plugin_t)) {
1808
                                                JANUS_LOG(LOG_WARN, "Error allowing access to '%s' to the new token, bad things may happen...\n", plugin_text);
1809
                                        }
1810
                                }
1811
                        } else {
1812
                                /* No plugin limitation specified, allow all plugins */
1813
                                if(plugins && g_hash_table_size(plugins) > 0) {
1814
                                        GHashTableIter iter;
1815
                                        gpointer value;
1816
                                        g_hash_table_iter_init(&iter, plugins);
1817
                                        while (g_hash_table_iter_next(&iter, NULL, &value)) {
1818
                                                janus_plugin *plugin_t = value;
1819
                                                if(plugin_t == NULL)
1820
                                                        continue;
1821
                                                if(!janus_auth_allow_plugin(token_value, plugin_t)) {
1822
                                                        JANUS_LOG(LOG_WARN, "Error allowing access to '%s' to the new token, bad things may happen...\n", plugin_t->get_package());
1823
                                                }
1824
                                        }
1825
                                }
1826
                        }
1827
                        /* Get the list of plugins this new token can access */
1828
                        json_t *plugins_list = json_array();
1829
                        GList *plugins = janus_auth_list_plugins(token_value);
1830
                        if(plugins != NULL) {
1831
                                GList *tmp = plugins;
1832
                                while(tmp) {
1833
                                        janus_plugin *p = (janus_plugin *)tmp->data;
1834
                                        if(p != NULL)
1835
                                                json_array_append_new(plugins_list, json_string(p->get_package()));
1836
                                        tmp = tmp->next;
1837
                                }
1838
                                g_list_free(plugins);
1839
                                plugins = NULL;
1840
                        }
1841
                        /* Prepare JSON reply */
1842
                        json_t *reply = json_object();
1843
                        json_object_set_new(reply, "janus", json_string("success"));
1844
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1845
                        json_t *data = json_object();
1846
                        json_object_set_new(data, "plugins", plugins_list);
1847
                        json_object_set_new(reply, "data", data);
1848
                        /* Send the success reply */
1849
                        ret = janus_process_success(request, reply);
1850
                        goto jsondone;
1851
                } else if(!strcasecmp(message_text, "list_tokens")) {
1852
                        /* List all the valid tokens */
1853
                        if(!janus_auth_is_enabled()) {
1854
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN, "Token based authentication disabled");
1855
                                goto jsondone;
1856
                        }
1857
                        json_t *tokens_list = json_array();
1858
                        GList *list = janus_auth_list_tokens();
1859
                        if(list != NULL) {
1860
                                GList *tmp = list;
1861
                                while(tmp) {
1862
                                        char *token = (char *)tmp->data;
1863
                                        if(token != NULL) {
1864
                                                GList *plugins = janus_auth_list_plugins(token);
1865
                                                if(plugins != NULL) {
1866
                                                        json_t *t = json_object();
1867
                                                        json_object_set_new(t, "token", json_string(token));
1868
                                                        json_t *plugins_list = json_array();
1869
                                                        GList *tmp2 = plugins;
1870
                                                        while(tmp2) {
1871
                                                                janus_plugin *p = (janus_plugin *)tmp2->data;
1872
                                                                if(p != NULL)
1873
                                                                        json_array_append_new(plugins_list, json_string(p->get_package()));
1874
                                                                tmp2 = tmp2->next;
1875
                                                        }
1876
                                                        g_list_free(plugins);
1877
                                                        plugins = NULL;
1878
                                                        json_object_set_new(t, "allowed_plugins", plugins_list);
1879
                                                        json_array_append_new(tokens_list, t);
1880
                                                }
1881
                                                tmp->data = NULL;
1882
                                                g_free(token);
1883
                                        }
1884
                                        tmp = tmp->next;
1885
                                }
1886
                                g_list_free(list);
1887
                        }
1888
                        /* Prepare JSON reply */
1889
                        json_t *reply = json_object();
1890
                        json_object_set_new(reply, "janus", json_string("success"));
1891
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1892
                        json_t *data = json_object();
1893
                        json_object_set_new(data, "tokens", tokens_list);
1894
                        json_object_set_new(reply, "data", data);
1895
                        /* Send the success reply */
1896
                        ret = janus_process_success(request, reply);
1897
                        goto jsondone;
1898
                } else if(!strcasecmp(message_text, "allow_token")) {
1899
                        /* Allow a valid token valid to access a plugin */
1900
                        if(!janus_auth_is_enabled()) {
1901
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN, "Token based authentication disabled");
1902
                                goto jsondone;
1903
                        }
1904
                        JANUS_VALIDATE_JSON_OBJECT(root, allow_token_parameters,
1905
                                error_code, error_cause, FALSE,
1906
                                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
1907
                        if(error_code != 0) {
1908
                                ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
1909
                                goto jsondone;
1910
                        }
1911
                        json_t *token = json_object_get(root, "token");
1912
                        const char *token_value = json_string_value(token);
1913
                        /* Check if the token is valid, first */
1914
                        if(!janus_auth_check_token(token_value)) {
1915
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_TOKEN_NOT_FOUND, "Token %s not found", token_value);
1916
                                goto jsondone;
1917
                        }
1918
                        /* Any plugin this token should be limited to? */
1919
                        json_t *allowed = json_object_get(root, "plugins");
1920
                        /* Check the list first */
1921
                        size_t i = 0;
1922
                        gboolean ok = TRUE;
1923
                        for(i=0; i<json_array_size(allowed); i++) {
1924
                                json_t *p = json_array_get(allowed, i);
1925
                                if(!p || !json_is_string(p)) {
1926
                                        /* FIXME Should we fail here? */
1927
                                        JANUS_LOG(LOG_ERR, "Invalid plugin passed to the new token request...\n");
1928
                                        ok = FALSE;
1929
                                        break;
1930
                                }
1931
                                const gchar *plugin_text = json_string_value(p);
1932
                                janus_plugin *plugin_t = janus_plugin_find(plugin_text);
1933
                                if(plugin_t == NULL) {
1934
                                        /* FIXME Should we fail here? */
1935
                                        JANUS_LOG(LOG_ERR, "No such plugin '%s' passed to the new token request...\n", plugin_text);
1936
                                        ok = FALSE;
1937
                                        break;
1938
                                }
1939
                        }
1940
                        if(!ok) {
1941
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_ELEMENT_TYPE, "Invalid element type (some of the provided plugins are invalid)");
1942
                                goto jsondone;
1943
                        }
1944
                        /* Take care of the plugins access limitations */
1945
                        i = 0;
1946
                        for(i=0; i<json_array_size(allowed); i++) {
1947
                                json_t *p = json_array_get(allowed, i);
1948
                                const gchar *plugin_text = json_string_value(p);
1949
                                janus_plugin *plugin_t = janus_plugin_find(plugin_text);
1950
                                if(!janus_auth_allow_plugin(token_value, plugin_t)) {
1951
                                        /* FIXME Should we notify individual failures? */
1952
                                        JANUS_LOG(LOG_WARN, "Error allowing access to '%s' to the new token, bad things may happen...\n", plugin_text);
1953
                                }
1954
                        }
1955
                        /* Get the list of plugins this new token can now access */
1956
                        json_t *plugins_list = json_array();
1957
                        GList *plugins = janus_auth_list_plugins(token_value);
1958
                        if(plugins != NULL) {
1959
                                GList *tmp = plugins;
1960
                                while(tmp) {
1961
                                        janus_plugin *p = (janus_plugin *)tmp->data;
1962
                                        if(p != NULL)
1963
                                                json_array_append_new(plugins_list, json_string(p->get_package()));
1964
                                        tmp = tmp->next;
1965
                                }
1966
                                g_list_free(plugins);
1967
                                plugins = NULL;
1968
                        }
1969
                        /* Prepare JSON reply */
1970
                        json_t *reply = json_object();
1971
                        json_object_set_new(reply, "janus", json_string("success"));
1972
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1973
                        json_t *data = json_object();
1974
                        json_object_set_new(data, "plugins", plugins_list);
1975
                        json_object_set_new(reply, "data", data);
1976
                        /* Send the success reply */
1977
                        ret = janus_process_success(request, reply);
1978
                        goto jsondone;
1979
                } else if(!strcasecmp(message_text, "disallow_token")) {
1980
                        /* Disallow a valid token valid from accessing a plugin */
1981
                        if(!janus_auth_is_enabled()) {
1982
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN, "Token based authentication disabled");
1983
                                goto jsondone;
1984
                        }
1985
                        JANUS_VALIDATE_JSON_OBJECT(root, allow_token_parameters,
1986
                                error_code, error_cause, FALSE,
1987
                                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
1988
                        if(error_code != 0) {
1989
                                ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
1990
                                goto jsondone;
1991
                        }
1992
                        json_t *token = json_object_get(root, "token");
1993
                        const char *token_value = json_string_value(token);
1994
                        /* Check if the token is valid, first */
1995
                        if(!janus_auth_check_token(token_value)) {
1996
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_TOKEN_NOT_FOUND, "Token %s not found", token_value);
1997
                                goto jsondone;
1998
                        }
1999
                        /* Any plugin this token should be prevented access to? */
2000
                        json_t *allowed = json_object_get(root, "plugins");
2001
                        /* Check the list first */
2002
                        size_t i = 0;
2003
                        gboolean ok = TRUE;
2004
                        for(i=0; i<json_array_size(allowed); i++) {
2005
                                json_t *p = json_array_get(allowed, i);
2006
                                if(!p || !json_is_string(p)) {
2007
                                        /* FIXME Should we fail here? */
2008
                                        JANUS_LOG(LOG_ERR, "Invalid plugin passed to the new token request...\n");
2009
                                        ok = FALSE;
2010
                                        break;
2011
                                }
2012
                                const gchar *plugin_text = json_string_value(p);
2013
                                janus_plugin *plugin_t = janus_plugin_find(plugin_text);
2014
                                if(plugin_t == NULL) {
2015
                                        /* FIXME Should we fail here? */
2016
                                        JANUS_LOG(LOG_ERR, "No such plugin '%s' passed to the new token request...\n", plugin_text);
2017
                                        ok = FALSE;
2018
                                        break;
2019
                                }
2020
                        }
2021
                        if(!ok) {
2022
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_ELEMENT_TYPE, "Invalid element type (some of the provided plugins are invalid)");
2023
                                goto jsondone;
2024
                        }
2025
                        /* Take care of the plugins access limitations */
2026
                        i = 0;
2027
                        for(i=0; i<json_array_size(allowed); i++) {
2028
                                json_t *p = json_array_get(allowed, i);
2029
                                const gchar *plugin_text = json_string_value(p);
2030
                                janus_plugin *plugin_t = janus_plugin_find(plugin_text);
2031
                                if(!janus_auth_disallow_plugin(token_value, plugin_t)) {
2032
                                        /* FIXME Should we notify individual failures? */
2033
                                        JANUS_LOG(LOG_WARN, "Error allowing access to '%s' to the new token, bad things may happen...\n", plugin_text);
2034
                                }
2035
                        }
2036
                        /* Get the list of plugins this new token can now access */
2037
                        json_t *plugins_list = json_array();
2038
                        GList *plugins = janus_auth_list_plugins(token_value);
2039
                        if(plugins != NULL) {
2040
                                GList *tmp = plugins;
2041
                                while(tmp) {
2042
                                        janus_plugin *p = (janus_plugin *)tmp->data;
2043
                                        if(p != NULL)
2044
                                                json_array_append_new(plugins_list, json_string(p->get_package()));
2045
                                        tmp = tmp->next;
2046
                                }
2047
                                g_list_free(plugins);
2048
                                plugins = NULL;
2049
                        }
2050
                        /* Prepare JSON reply */
2051
                        json_t *reply = json_object();
2052
                        json_object_set_new(reply, "janus", json_string("success"));
2053
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
2054
                        json_t *data = json_object();
2055
                        json_object_set_new(data, "plugins", plugins_list);
2056
                        json_object_set_new(reply, "data", data);
2057
                        /* Send the success reply */
2058
                        ret = janus_process_success(request, reply);
2059
                        goto jsondone;
2060
                } else if(!strcasecmp(message_text, "remove_token")) {
2061
                        /* Invalidate a token for authentication purposes */
2062
                        if(!janus_auth_is_enabled()) {
2063
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN, "Token based authentication disabled");
2064
                                goto jsondone;
2065
                        }
2066
                        JANUS_VALIDATE_JSON_OBJECT(root, token_parameters,
2067
                                error_code, error_cause, FALSE,
2068
                                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
2069
                        if(error_code != 0) {
2070
                                ret = janus_process_error_string(request, session_id, transaction_text, error_code, error_cause);
2071
                                goto jsondone;
2072
                        }
2073
                        json_t *token = json_object_get(root, "token");
2074
                        const char *token_value = json_string_value(token);
2075
                        if(!janus_auth_remove_token(token_value)) {
2076
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN, "Error removing token");
2077
                                goto jsondone;
2078
                        }
2079
                        /* Prepare JSON reply */
2080
                        json_t *reply = json_object();
2081
                        json_object_set_new(reply, "janus", json_string("success"));
2082
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
2083
                        /* Send the success reply */
2084
                        ret = janus_process_success(request, reply);
2085
                        goto jsondone;
2086
                } else {
2087
                        /* No message we know of */
2088
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
2089
                        goto jsondone;
2090
                }
2091
        }
2092
        if(session_id < 1) {
2093
                JANUS_LOG(LOG_ERR, "Invalid session\n");
2094
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, NULL);
2095
                goto jsondone;
2096
        }
2097
        if(h && handle_id < 1) {
2098
                JANUS_LOG(LOG_ERR, "Invalid handle\n");
2099
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, NULL);
2100
                goto jsondone;
2101
        }
2102

    
2103
        /* Go on with the processing */
2104
        if(admin_api_secret != NULL) {
2105
                /* There's an API secret, check that the client provided it */
2106
                json_t *secret = json_object_get(root, "admin_secret");
2107
                if(!secret || !json_is_string(secret) || !janus_strcmp_const_time(json_string_value(secret), admin_api_secret)) {
2108
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNAUTHORIZED, NULL);
2109
                        goto jsondone;
2110
                }
2111
        }
2112

    
2113
        /* If we got here, make sure we have a session (and/or a handle) */
2114
        janus_session *session = janus_session_find(session_id);
2115
        if(!session) {
2116
                JANUS_LOG(LOG_ERR, "Couldn't find any session %"SCNu64"...\n", session_id);
2117
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, "No such session %"SCNu64"", session_id);
2118
                goto jsondone;
2119
        }
2120
        janus_ice_handle *handle = NULL;
2121
        if(handle_id > 0) {
2122
                handle = janus_ice_handle_find(session, handle_id);
2123
                if(!handle) {
2124
                        JANUS_LOG(LOG_ERR, "Couldn't find any handle %"SCNu64" in session %"SCNu64"...\n", handle_id, session_id);
2125
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_HANDLE_NOT_FOUND, "No such handle %"SCNu64" in session %"SCNu64"", handle_id, session_id);
2126
                        goto jsondone;
2127
                }
2128
        }
2129

    
2130
        /* What is this? */
2131
        if(handle == NULL) {
2132
                /* Session-related */
2133
                if(strcasecmp(message_text, "list_handles")) {
2134
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
2135
                        goto jsondone;
2136
                }
2137
                /* List handles */
2138
                json_t *list = json_array();
2139
                if(session->ice_handles != NULL && g_hash_table_size(session->ice_handles) > 0) {
2140
                        GHashTableIter iter;
2141
                        gpointer value;
2142
                        janus_mutex_lock(&session->mutex);
2143
                        g_hash_table_iter_init(&iter, session->ice_handles);
2144
                        while (g_hash_table_iter_next(&iter, NULL, &value)) {
2145
                                janus_ice_handle *handle = value;
2146
                                if(handle == NULL) {
2147
                                        continue;
2148
                                }
2149
                                json_array_append_new(list, json_integer(handle->handle_id));
2150
                        }
2151
                        janus_mutex_unlock(&session->mutex);
2152
                }
2153
                /* Prepare JSON reply */
2154
                json_t *reply = json_object();
2155
                json_object_set_new(reply, "janus", json_string("success"));
2156
                json_object_set_new(reply, "transaction", json_string(transaction_text));
2157
                json_object_set_new(reply, "session_id", json_integer(session_id));
2158
                json_object_set_new(reply, "handles", list);
2159
                /* Send the success reply */
2160
                ret = janus_process_success(request, reply);
2161
                goto jsondone;
2162
        } else {
2163
                /* Handle-related */
2164
                if(strcasecmp(message_text, "handle_info")) {
2165
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
2166
                        goto jsondone;
2167
                }
2168
                /* Prepare info */
2169
                janus_mutex_lock(&handle->mutex);
2170
                json_t *info = json_object();
2171
                json_object_set_new(info, "session_id", json_integer(session_id));
2172
                json_object_set_new(info, "session_last_activity", json_integer(session->last_activity));
2173
                if(session->source && session->source->transport)
2174
                        json_object_set_new(info, "session_transport", json_string(session->source->transport->get_package()));
2175
                json_object_set_new(info, "handle_id", json_integer(handle_id));
2176
                if(handle->opaque_id)
2177
                        json_object_set_new(info, "opaque_id", json_string(handle->opaque_id));
2178
                json_object_set_new(info, "created", json_integer(handle->created));
2179
                json_object_set_new(info, "send_thread_created", g_atomic_int_get(&handle->send_thread_created) ? json_true() : json_false());
2180
                json_object_set_new(info, "current_time", json_integer(janus_get_monotonic_time()));
2181
                if(handle->app && handle->app_handle && janus_plugin_session_is_alive(handle->app_handle)) {
2182
                        janus_plugin *plugin = (janus_plugin *)handle->app;
2183
                        json_object_set_new(info, "plugin", json_string(plugin->get_package()));
2184
                        if(plugin->query_session) {
2185
                                /* FIXME This check will NOT work with legacy plugins that were compiled BEFORE the method was specified in plugin.h */
2186
                                json_t *query = plugin->query_session(handle->app_handle);
2187
                                if(query != NULL) {
2188
                                        /* Make sure this is a JSON object */
2189
                                        if(!json_is_object(query)) {
2190
                                                JANUS_LOG(LOG_WARN, "Ignoring invalid query response from the plugin (not an object)\n");
2191
                                                json_decref(query);
2192
                                        } else {
2193
                                                json_object_set_new(info, "plugin_specific", query);
2194
                                        }
2195
                                        query = NULL;
2196
                                }
2197
                        }
2198
                }
2199
                json_t *flags = json_object();
2200
                json_object_set_new(flags, "got-offer", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_OFFER) ? json_true() : json_false());
2201
                json_object_set_new(flags, "got-answer", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_ANSWER) ? json_true() : json_false());
2202
                json_object_set_new(flags, "processing-offer", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER) ? json_true() : json_false());
2203
                json_object_set_new(flags, "starting", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_START) ? json_true() : json_false());
2204
                json_object_set_new(flags, "ready", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_READY) ? json_true() : json_false());
2205
                json_object_set_new(flags, "stopped", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP) ? json_true() : json_false());
2206
                json_object_set_new(flags, "alert", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT) ? json_true() : json_false());
2207
                json_object_set_new(flags, "bundle", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE) ? json_true() : json_false());
2208
                json_object_set_new(flags, "rtcp-mux", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_RTCPMUX) ? json_true() : json_false());
2209
                json_object_set_new(flags, "trickle", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_TRICKLE) ? json_true() : json_false());
2210
                json_object_set_new(flags, "all-trickles", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALL_TRICKLES) ? json_true() : json_false());
2211
                json_object_set_new(flags, "trickle-synced", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_TRICKLE_SYNCED) ? json_true() : json_false());
2212
                json_object_set_new(flags, "data-channels", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_DATA_CHANNELS) ? json_true() : json_false());
2213
                json_object_set_new(flags, "has-audio", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_AUDIO) ? json_true() : json_false());
2214
                json_object_set_new(flags, "has-video", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_VIDEO) ? json_true() : json_false());
2215
                json_object_set_new(flags, "plan-b", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PLAN_B) ? json_true() : json_false());
2216
                json_object_set_new(flags, "cleaning", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_CLEANING) ? json_true() : json_false());
2217
                json_object_set_new(info, "flags", flags);
2218
                if(handle->agent) {
2219
                        json_object_set_new(info, "agent-created", json_integer(handle->agent_created));
2220
                        json_object_set_new(info, "ice-mode", json_string(janus_ice_is_ice_lite_enabled() ? "lite" : "full"));
2221
                        json_object_set_new(info, "ice-role", json_string(handle->controlling ? "controlling" : "controlled"));
2222
                }
2223
                json_t *sdps = json_object();
2224
                if(handle->rtp_profile)
2225
                        json_object_set_new(sdps, "profile", json_string(handle->rtp_profile));
2226
                if(handle->local_sdp)
2227
                        json_object_set_new(sdps, "local", json_string(handle->local_sdp));
2228
                if(handle->remote_sdp)
2229
                        json_object_set_new(sdps, "remote", json_string(handle->remote_sdp));
2230
                json_object_set_new(info, "sdps", sdps);
2231
                if(handle->pending_trickles)
2232
                        json_object_set_new(info, "pending-trickles", json_integer(g_list_length(handle->pending_trickles)));
2233
                if(handle->queued_packets)
2234
                        json_object_set_new(info, "queued-packets", json_integer(g_async_queue_length(handle->queued_packets)));
2235
                json_t *streams = json_array();
2236
                if(handle->audio_stream) {
2237
                        json_t *s = janus_admin_stream_summary(handle->audio_stream);
2238
                        if(s)
2239
                                json_array_append_new(streams, s);
2240
                }
2241
                if(handle->video_stream) {
2242
                        json_t *s = janus_admin_stream_summary(handle->video_stream);
2243
                        if(s)
2244
                                json_array_append_new(streams, s);
2245
                }
2246
                if(handle->data_stream) {
2247
                        json_t *s = janus_admin_stream_summary(handle->data_stream);
2248
                        if(s)
2249
                                json_array_append_new(streams, s);
2250
                }
2251
                json_object_set_new(info, "streams", streams);
2252
                janus_mutex_unlock(&handle->mutex);
2253
                /* Prepare JSON reply */
2254
                json_t *reply = json_object();
2255
                json_object_set_new(reply, "janus", json_string("success"));
2256
                json_object_set_new(reply, "transaction", json_string(transaction_text));
2257
                json_object_set_new(reply, "session_id", json_integer(session_id));
2258
                json_object_set_new(reply, "handle_id", json_integer(handle_id));
2259
                json_object_set_new(reply, "info", info);
2260
                /* Send the success reply */
2261
                ret = janus_process_success(request, reply);
2262
                goto jsondone;
2263
        }
2264

    
2265
jsondone:
2266
        /* Done processing */
2267
        return ret;
2268
}
2269

    
2270
int janus_process_success(janus_request *request, json_t *payload)
2271
{
2272
        if(!request || !payload)
2273
                return -1;
2274
        /* Pass to the right transport plugin */
2275
        JANUS_LOG(LOG_HUGE, "Sending %s API response to %s (%p)\n", request->admin ? "admin" : "Janus", request->transport->get_package(), request->instance);
2276
        return request->transport->send_message(request->instance, request->request_id, request->admin, payload);
2277
}
2278

    
2279
static int janus_process_error_string(janus_request *request, uint64_t session_id, const char *transaction, gint error, gchar *error_string)
2280
{
2281
        if(!request)
2282
                return -1;
2283
        /* Done preparing error */
2284
        JANUS_LOG(LOG_VERB, "[%s] Returning %s API error %d (%s)\n", transaction, request->admin ? "admin" : "Janus", error, error_string);
2285
        /* Prepare JSON error */
2286
        json_t *reply = json_object();
2287
        json_object_set_new(reply, "janus", json_string("error"));
2288
        if(session_id > 0)
2289
                json_object_set_new(reply, "session_id", json_integer(session_id));
2290
        if(transaction != NULL)
2291
                json_object_set_new(reply, "transaction", json_string(transaction));
2292
        json_t *error_data = json_object();
2293
        json_object_set_new(error_data, "code", json_integer(error));
2294
        json_object_set_new(error_data, "reason", json_string(error_string));
2295
        json_object_set_new(reply, "error", error_data);
2296
        /* Pass to the right transport plugin */
2297
        return request->transport->send_message(request->instance, request->request_id, request->admin, reply);
2298
}
2299

    
2300
int janus_process_error(janus_request *request, uint64_t session_id, const char *transaction, gint error, const char *format, ...)
2301
{
2302
        if(!request)
2303
                return -1;
2304
        gchar *error_string = NULL;
2305
        gchar error_buf[512];
2306
        if(format == NULL) {
2307
                /* No error string provided, use the default one */
2308
                error_string = (gchar *)janus_get_api_error(error);
2309
        } else {
2310
                /* This callback has variable arguments (error string) */
2311
                va_list ap;
2312
                va_start(ap, format);
2313
                g_vsnprintf(error_buf, sizeof(error_buf), format, ap);
2314
                va_end(ap);
2315
                error_string = error_buf;
2316
        }
2317
        return janus_process_error_string(request, session_id, transaction, error, error_string);
2318
}
2319

    
2320
/* Admin/monitor helpers */
2321
json_t *janus_admin_stream_summary(janus_ice_stream *stream) {
2322
        if(stream == NULL)
2323
                return NULL;
2324
        json_t *s = json_object();
2325
        json_object_set_new(s, "id", json_integer(stream->stream_id));
2326
        json_object_set_new(s, "ready", json_integer(stream->cdone));
2327
        json_object_set_new(s, "disabled", stream->disabled ? json_true() : json_false());
2328
        json_t *ss = json_object();
2329
        if(stream->audio_ssrc)
2330
                json_object_set_new(ss, "audio", json_integer(stream->audio_ssrc));
2331
        if(stream->video_ssrc)
2332
                json_object_set_new(ss, "video", json_integer(stream->video_ssrc));
2333
        if(stream->audio_ssrc_peer)
2334
                json_object_set_new(ss, "audio-peer", json_integer(stream->audio_ssrc_peer));
2335
        if(stream->video_ssrc_peer)
2336
                json_object_set_new(ss, "video-peer", json_integer(stream->video_ssrc_peer));
2337
        if(stream->video_ssrc_peer_rtx)
2338
                json_object_set_new(ss, "video-peer-rtx", json_integer(stream->video_ssrc_peer_rtx));
2339
        json_object_set_new(s, "ssrc", ss);
2340
        json_t *components = json_array();
2341
        if(stream->rtp_component) {
2342
                json_t *c = janus_admin_component_summary(stream->rtp_component);
2343
                if(c)
2344
                        json_array_append_new(components, c);
2345
        }
2346
        if(stream->rtcp_component) {
2347
                json_t *c = janus_admin_component_summary(stream->rtcp_component);
2348
                if(c)
2349
                        json_array_append_new(components, c);
2350
        }
2351
        json_t *rtcp_stats = NULL;
2352
        if(stream->audio_rtcp_ctx != NULL) {
2353
                rtcp_stats = json_object();
2354
                json_t *audio_rtcp_stats = json_object();
2355
                json_object_set_new(audio_rtcp_stats, "base", json_integer(stream->audio_rtcp_ctx->tb));
2356
                json_object_set_new(audio_rtcp_stats, "lsr", json_integer(janus_rtcp_context_get_lsr(stream->audio_rtcp_ctx)));
2357
                json_object_set_new(audio_rtcp_stats, "lost", json_integer(janus_rtcp_context_get_lost_all(stream->audio_rtcp_ctx, FALSE)));
2358
                json_object_set_new(audio_rtcp_stats, "lost-by-remote", json_integer(janus_rtcp_context_get_lost_all(stream->audio_rtcp_ctx, TRUE)));
2359
                json_object_set_new(audio_rtcp_stats, "jitter-local", json_integer(janus_rtcp_context_get_jitter(stream->audio_rtcp_ctx, FALSE)));
2360
                json_object_set_new(audio_rtcp_stats, "jitter-remote", json_integer(janus_rtcp_context_get_jitter(stream->audio_rtcp_ctx, TRUE)));
2361
                json_object_set_new(rtcp_stats, "audio", audio_rtcp_stats);
2362
        }
2363
        if(stream->video_rtcp_ctx != NULL) {
2364
                if(rtcp_stats == NULL)
2365
                        rtcp_stats = json_object();
2366
                json_t *video_rtcp_stats = json_object();
2367
                json_object_set_new(video_rtcp_stats, "base", json_integer(stream->video_rtcp_ctx->tb));
2368
                json_object_set_new(video_rtcp_stats, "lsr", json_integer(janus_rtcp_context_get_lsr(stream->video_rtcp_ctx)));
2369
                json_object_set_new(video_rtcp_stats, "lost", json_integer(janus_rtcp_context_get_lost_all(stream->video_rtcp_ctx, FALSE)));
2370
                json_object_set_new(video_rtcp_stats, "lost-by-remote", json_integer(janus_rtcp_context_get_lost_all(stream->video_rtcp_ctx, TRUE)));
2371
                json_object_set_new(video_rtcp_stats, "jitter-local", json_integer(janus_rtcp_context_get_jitter(stream->video_rtcp_ctx, FALSE)));
2372
                json_object_set_new(video_rtcp_stats, "jitter-remote", json_integer(janus_rtcp_context_get_jitter(stream->video_rtcp_ctx, TRUE)));
2373
                json_object_set_new(rtcp_stats, "video", video_rtcp_stats);
2374
        }
2375
        if(rtcp_stats != NULL)
2376
                json_object_set_new(s, "rtcp_stats", rtcp_stats);
2377
        json_object_set_new(s, "components", components);
2378
        return s;
2379
}
2380

    
2381
json_t *janus_admin_component_summary(janus_ice_component *component) {
2382
        if(component == NULL)
2383
                return NULL;
2384
        janus_ice_handle *handle = component->stream ? component->stream->handle : NULL;
2385
        json_t *c = json_object();
2386
        json_object_set_new(c, "id", json_integer(component->component_id));
2387
        json_object_set_new(c, "state", json_string(janus_get_ice_state_name(component->state)));
2388
        if(component->component_connected > 0)
2389
                json_object_set_new(c, "connected", json_integer(component->component_connected));
2390
        if(component->local_candidates) {
2391
                json_t *cs = json_array();
2392
                GSList *candidates = component->local_candidates, *i = NULL;
2393
                for (i = candidates; i; i = i->next) {
2394
                        gchar *lc = (gchar *) i->data;
2395
                        if(lc)
2396
                                json_array_append_new(cs, json_string(lc));
2397
                }
2398
                json_object_set_new(c, "local-candidates", cs);
2399
        }
2400
        if(component->remote_candidates) {
2401
                json_t *cs = json_array();
2402
                GSList *candidates = component->remote_candidates, *i = NULL;
2403
                for (i = candidates; i; i = i->next) {
2404
                        gchar *rc = (gchar *) i->data;
2405
                        if(rc)
2406
                                json_array_append_new(cs, json_string(rc));
2407
                }
2408
                json_object_set_new(c, "remote-candidates", cs);
2409
        }
2410
        if(component->selected_pair) {
2411
                json_object_set_new(c, "selected-pair", json_string(component->selected_pair));
2412
        }
2413
        json_t *d = json_object();
2414
        json_t *in_stats = json_object();
2415
        json_t *out_stats = json_object();
2416
        if(component->dtls) {
2417
                janus_dtls_srtp *dtls = component->dtls;
2418
                json_object_set_new(d, "fingerprint", json_string(janus_dtls_get_local_fingerprint()));
2419
                json_object_set_new(d, "remote-fingerprint", json_string(component->stream->remote_fingerprint));
2420
                json_object_set_new(d, "remote-fingerprint-hash", json_string(component->stream->remote_hashing));
2421
                json_object_set_new(d, "dtls-role", json_string(janus_get_dtls_srtp_role(component->stream->dtls_role)));
2422
                json_object_set_new(d, "dtls-state", json_string(janus_get_dtls_srtp_state(dtls->dtls_state)));
2423
                json_object_set_new(d, "retransmissions", json_integer(dtls->retransmissions));
2424
                json_object_set_new(d, "valid", dtls->srtp_valid ? json_true() : json_false());
2425
                json_object_set_new(d, "ready", dtls->ready ? json_true() : json_false());
2426
                if(dtls->dtls_connected > 0)
2427
                        json_object_set_new(d, "connected", json_integer(dtls->dtls_connected));
2428
                if(handle && janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_AUDIO)) {
2429
                        json_object_set_new(in_stats, "audio_packets", json_integer(component->in_stats.audio_packets));
2430
                        json_object_set_new(in_stats, "audio_bytes", json_integer(component->in_stats.audio_bytes));
2431
                        json_object_set_new(in_stats, "audio_nacks", json_integer(component->in_stats.audio_nacks));
2432
                        /* Compute the last second stuff too */
2433
                        gint64 now = janus_get_monotonic_time();
2434
                        guint64 bytes = 0;
2435
                        if(component->in_stats.audio_bytes_lastsec) {
2436
                                GList *lastsec = component->in_stats.audio_bytes_lastsec;
2437
                                while(lastsec) {
2438
                                        janus_ice_stats_item *s = (janus_ice_stats_item *)lastsec->data;
2439
                                        if(s && now-s->when < G_USEC_PER_SEC)
2440
                                                bytes += s->bytes;
2441
                                        lastsec = lastsec->next;
2442
                                }
2443
                        }
2444
                        json_object_set_new(in_stats, "audio_bytes_lastsec", json_integer(bytes));
2445
                }
2446
                if(handle && janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_VIDEO)) {
2447
                        json_object_set_new(in_stats, "video_packets", json_integer(component->in_stats.video_packets));
2448
                        json_object_set_new(in_stats, "video_bytes", json_integer(component->in_stats.video_bytes));
2449
                        json_object_set_new(in_stats, "video_nacks", json_integer(component->in_stats.video_nacks));
2450
                        /* Compute the last second stuff too */
2451
                        gint64 now = janus_get_monotonic_time();
2452
                        guint64 bytes = 0;
2453
                        if(component->in_stats.video_bytes_lastsec) {
2454
                                GList *lastsec = component->in_stats.video_bytes_lastsec;
2455
                                while(lastsec) {
2456
                                        janus_ice_stats_item *s = (janus_ice_stats_item *)lastsec->data;
2457
                                        if(s && now-s->when < G_USEC_PER_SEC)
2458
                                                bytes += s->bytes;
2459
                                        lastsec = lastsec->next;
2460
                                }
2461
                        }
2462
                        json_object_set_new(in_stats, "video_bytes_lastsec", json_integer(bytes));
2463
                }
2464
                json_object_set_new(in_stats, "data_packets", json_integer(component->in_stats.data_packets));
2465
                json_object_set_new(in_stats, "data_bytes", json_integer(component->in_stats.data_bytes));
2466
                if(handle && janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_AUDIO)) {
2467
                        json_object_set_new(out_stats, "audio_packets", json_integer(component->out_stats.audio_packets));
2468
                        json_object_set_new(out_stats, "audio_bytes", json_integer(component->out_stats.audio_bytes));
2469
                        json_object_set_new(out_stats, "audio_nacks", json_integer(component->out_stats.audio_nacks));
2470
                }
2471
                if(handle && janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_VIDEO)) {
2472
                        json_object_set_new(out_stats, "video_packets", json_integer(component->out_stats.video_packets));
2473
                        json_object_set_new(out_stats, "video_bytes", json_integer(component->out_stats.video_bytes));
2474
                        json_object_set_new(out_stats, "video_nacks", json_integer(component->out_stats.video_nacks));
2475
                }
2476
                json_object_set_new(out_stats, "data_packets", json_integer(component->out_stats.data_packets));
2477
                json_object_set_new(out_stats, "data_bytes", json_integer(component->out_stats.data_bytes));
2478
#ifdef HAVE_SCTP
2479
                /* FIXME Actually check if this succeeded? */
2480
                json_object_set_new(d, "sctp-association", dtls->sctp ? json_true() : json_false());
2481
#endif
2482
        }
2483
        json_object_set_new(c, "dtls", d);
2484
        json_object_set_new(c, "in_stats", in_stats);
2485
        json_object_set_new(c, "out_stats", out_stats);
2486
        return c;
2487
}
2488

    
2489

    
2490
/* Transports */
2491
void janus_transport_close(gpointer key, gpointer value, gpointer user_data) {
2492
        janus_transport *transport = (janus_transport *)value;
2493
        if(!transport)
2494
                return;
2495
        transport->destroy();
2496
}
2497

    
2498
void janus_transportso_close(gpointer key, gpointer value, gpointer user_data) {
2499
        void *transport = value;
2500
        if(!transport)
2501
                return;
2502
        /* FIXME We don't dlclose transports to be sure we can detect leaks */
2503
        //~ dlclose(transport);
2504
}
2505

    
2506
/* Transport callback interface */
2507
void janus_transport_incoming_request(janus_transport *plugin, void *transport, void *request_id, gboolean admin, json_t *message, json_error_t *error) {
2508
        JANUS_LOG(LOG_VERB, "Got %s API request from %s (%p)\n", admin ? "an admin" : "a Janus", plugin->get_package(), transport);
2509
        /* Create a janus_request instance to handle the request */
2510
        janus_request *request = janus_request_new(plugin, transport, request_id, admin, message);
2511
        GError *tperror = NULL;
2512
        g_thread_pool_push(tasks, request, &tperror);
2513
        if(tperror != NULL) {
2514
                /* Something went wrong... */
2515
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to push task in thread pool...\n", tperror->code, tperror->message ? tperror->message : "??");
2516
                json_t *transaction = json_object_get(message, "transaction");
2517
                const char *transaction_text = json_is_string(transaction) ? json_string_value(transaction) : NULL;
2518
                janus_process_error(request, 0, transaction_text, JANUS_ERROR_UNKNOWN, "Thread pool error");
2519
                janus_request_destroy(request);
2520
        }
2521
}
2522

    
2523
void janus_transport_gone(janus_transport *plugin, void *transport) {
2524
        /* Get rid of sessions this transport was handling */
2525
        JANUS_LOG(LOG_VERB, "A %s transport instance has gone away (%p)\n", plugin->get_package(), transport);
2526
        janus_mutex_lock(&sessions_mutex);
2527
        if(sessions && g_hash_table_size(sessions) > 0) {
2528
                GHashTableIter iter;
2529
                gpointer value;
2530
                g_hash_table_iter_init(&iter, sessions);
2531
                while(g_hash_table_iter_next(&iter, NULL, &value)) {
2532
                        janus_session *session = (janus_session *) value;
2533
                        if(!session || session->destroy || session->timeout || session->last_activity == 0)
2534
                                continue;
2535
                        if(session->source && session->source->instance == transport) {
2536
                                JANUS_LOG(LOG_VERB, "  -- Marking Session %"SCNu64" as over\n", session->session_id);
2537
                                session->last_activity = 0;        /* This will trigger a timeout */
2538
                        }
2539
                }
2540
        }
2541
        janus_mutex_unlock(&sessions_mutex);
2542
}
2543

    
2544
gboolean janus_transport_is_api_secret_needed(janus_transport *plugin) {
2545
        return api_secret != NULL;
2546
}
2547

    
2548
gboolean janus_transport_is_api_secret_valid(janus_transport *plugin, const char *apisecret) {
2549
        if(api_secret == NULL)
2550
                return TRUE;
2551
        return apisecret && janus_strcmp_const_time(apisecret, api_secret);
2552
}
2553

    
2554
gboolean janus_transport_is_auth_token_needed(janus_transport *plugin) {
2555
        return janus_auth_is_enabled();
2556
}
2557

    
2558
gboolean janus_transport_is_auth_token_valid(janus_transport *plugin, const char *token) {
2559
        if(!janus_auth_is_enabled())
2560
                return TRUE;
2561
        return token && janus_auth_check_token(token);
2562
}
2563

    
2564
void janus_transport_notify_event(janus_transport *plugin, void *transport, json_t *event) {
2565
        /* A plugin asked to notify an event to the handlers */
2566
        if(!plugin || !event || !json_is_object(event))
2567
                return;
2568
        /* Notify event handlers */
2569
        if(janus_events_is_enabled()) {
2570
                janus_events_notify_handlers(JANUS_EVENT_TYPE_TRANSPORT,
2571
                        0, plugin->get_package(), transport, event);
2572
        } else {
2573
                json_decref(event);
2574
        }
2575
}
2576

    
2577
void janus_transport_task(gpointer data, gpointer user_data) {
2578
        JANUS_LOG(LOG_VERB, "Transport task pool, serving request\n");
2579
        janus_request *request = (janus_request *)data;
2580
        if(request == NULL) {
2581
                JANUS_LOG(LOG_ERR, "Missing request\n");
2582
                return;
2583
        }
2584
        if(!request->admin)
2585
                janus_process_incoming_request(request);
2586
        else
2587
                janus_process_incoming_admin_request(request);
2588
        /* Done */
2589
        janus_request_destroy(request);
2590
}
2591

    
2592

    
2593
/* Event handlers */
2594
void janus_eventhandler_close(gpointer key, gpointer value, gpointer user_data) {
2595
        janus_eventhandler *eventhandler = (janus_eventhandler *)value;
2596
        if(!eventhandler)
2597
                return;
2598
        eventhandler->destroy();
2599
}
2600

    
2601
void janus_eventhandlerso_close(gpointer key, gpointer value, gpointer user_data) {
2602
        void *eventhandler = (janus_eventhandler *)value;
2603
        if(!eventhandler)
2604
                return;
2605
        //~ dlclose(eventhandler);
2606
}
2607

    
2608

    
2609
/* Plugins */
2610
void janus_plugin_close(gpointer key, gpointer value, gpointer user_data) {
2611
        janus_plugin *plugin = (janus_plugin *)value;
2612
        if(!plugin)
2613
                return;
2614
        plugin->destroy();
2615
}
2616

    
2617
void janus_pluginso_close(gpointer key, gpointer value, gpointer user_data) {
2618
        void *plugin = value;
2619
        if(!plugin)
2620
                return;
2621
        /* FIXME We don't dlclose plugins to be sure we can detect leaks */
2622
        //~ dlclose(plugin);
2623
}
2624

    
2625
janus_plugin *janus_plugin_find(const gchar *package) {
2626
        if(package != NULL && plugins != NULL)        /* FIXME Do we need to fix the key pointer? */
2627
                return g_hash_table_lookup(plugins, package);
2628
        return NULL;
2629
}
2630

    
2631

    
2632
/* Plugin callback interface */
2633
int janus_plugin_push_event(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *transaction, json_t *message, json_t *jsep) {
2634
        if(!plugin || !message)
2635
                return -1;
2636
        if(!plugin_session || plugin_session < (janus_plugin_session *)0x1000 ||
2637
                        !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped)
2638
                return -2;
2639
        janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
2640
        if(!ice_handle || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP))
2641
                return JANUS_ERROR_SESSION_NOT_FOUND;
2642
        janus_session *session = ice_handle->session;
2643
        if(!session || session->destroy)
2644
                return JANUS_ERROR_SESSION_NOT_FOUND;
2645
        /* Make sure this is a JSON object */
2646
        if(!json_is_object(message)) {
2647
                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Cannot push event (JSON error: not an object)\n", ice_handle->handle_id);
2648
                return JANUS_ERROR_INVALID_JSON_OBJECT;
2649
        }
2650
        /* Attach JSEP if possible? */
2651
        const char *sdp_type = json_string_value(json_object_get(jsep, "type"));
2652
        const char *sdp = json_string_value(json_object_get(jsep, "sdp"));
2653
        json_t *merged_jsep = NULL;
2654
        if(sdp_type != NULL && sdp != NULL) {
2655
                merged_jsep = janus_plugin_handle_sdp(plugin_session, plugin, sdp_type, sdp);
2656
                if(merged_jsep == NULL) {
2657
                        if(ice_handle == NULL || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
2658
                                        || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT)) {
2659
                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Cannot push event (handle not available anymore or negotiation stopped)\n", ice_handle->handle_id);
2660
                                return JANUS_ERROR_HANDLE_NOT_FOUND;
2661
                        } else {
2662
                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Cannot push event (JSON error: problem with the SDP)\n", ice_handle->handle_id);
2663
                                return JANUS_ERROR_JSEP_INVALID_SDP;
2664
                        }
2665
                }
2666
        }
2667
        /* Reference the payload, as the plugin may still need it and will do a decref itself */
2668
        json_incref(message);
2669
        /* Prepare JSON event */
2670
        json_t *event = json_object();
2671
        json_object_set_new(event, "janus", json_string("event"));
2672
        json_object_set_new(event, "session_id", json_integer(session->session_id));
2673
        json_object_set_new(event, "sender", json_integer(ice_handle->handle_id));
2674
        if(transaction != NULL)
2675
                json_object_set_new(event, "transaction", json_string(transaction));
2676
        json_t *plugin_data = json_object();
2677
        json_object_set_new(plugin_data, "plugin", json_string(plugin->get_package()));
2678
        json_object_set_new(plugin_data, "data", message);
2679
        json_object_set_new(event, "plugindata", plugin_data);
2680
        if(merged_jsep != NULL)
2681
                json_object_set_new(event, "jsep", merged_jsep);
2682
        /* Send the event */
2683
        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Sending event to transport...\n", ice_handle->handle_id);
2684
        janus_session_notify_event(session->session_id, event);
2685

    
2686
        if(jsep != NULL && janus_events_is_enabled()) {
2687
                /* Notify event handlers as well */
2688
                janus_events_notify_handlers(JANUS_EVENT_TYPE_JSEP,
2689
                        session->session_id, ice_handle->handle_id, "local", sdp_type, sdp);
2690
        }
2691

    
2692
        return JANUS_OK;
2693
}
2694

    
2695
json_t *janus_plugin_handle_sdp(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *sdp_type, const char *sdp) {
2696
        if(!plugin_session || plugin_session < (janus_plugin_session *)0x1000 ||
2697
                        !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped ||
2698
                        plugin == NULL || sdp_type == NULL || sdp == NULL) {
2699
                JANUS_LOG(LOG_ERR, "Invalid arguments\n");
2700
                return NULL;
2701
        }
2702
        janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
2703
        //~ if(ice_handle == NULL || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_READY)) {
2704
        if(ice_handle == NULL) {
2705
                JANUS_LOG(LOG_ERR, "Invalid ICE handle\n");
2706
                return NULL;
2707
        }
2708
        int offer = 0;
2709
        if(!strcasecmp(sdp_type, "offer")) {
2710
                /* This is an offer from a plugin */
2711
                offer = 1;
2712
                janus_flags_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_OFFER);
2713
                janus_flags_clear(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_ANSWER);
2714
        } else if(!strcasecmp(sdp_type, "answer")) {
2715
                /* This is an answer from a plugin */
2716
                janus_flags_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_ANSWER);
2717
        } else {
2718
                /* TODO Handle other messages */
2719
                JANUS_LOG(LOG_ERR, "Unknown type '%s'\n", sdp_type);
2720
                return NULL;
2721
        }
2722
        /* Is this valid SDP? */
2723
        char error_str[512];
2724
        int audio = 0, video = 0, data = 0, bundle = 0, rtcpmux = 0, trickle = 0;
2725
        janus_sdp *parsed_sdp = janus_sdp_preparse(sdp, error_str, sizeof(error_str), &audio, &video, &data, &bundle, &rtcpmux, &trickle);
2726
        if(parsed_sdp == NULL) {
2727
                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Couldn't parse SDP... %s\n", ice_handle->handle_id, error_str);
2728
                return NULL;
2729
        }
2730
        gboolean updating = FALSE;
2731
        if(offer) {
2732
                /* We still don't have a local ICE setup */
2733
                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Audio %s been negotiated\n", ice_handle->handle_id, audio ? "has" : "has NOT");
2734
                if(audio > 1) {
2735
                        JANUS_LOG(LOG_ERR, "[%"SCNu64"] More than one audio line? only going to negotiate one...\n", ice_handle->handle_id);
2736
                }
2737
                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Video %s been negotiated\n", ice_handle->handle_id, video ? "has" : "has NOT");
2738
                if(video > 1) {
2739
                        JANUS_LOG(LOG_ERR, "[%"SCNu64"] More than one video line? only going to negotiate one...\n", ice_handle->handle_id);
2740
                }
2741
                JANUS_LOG(LOG_VERB, "[%"SCNu64"] SCTP/DataChannels %s been negotiated\n", ice_handle->handle_id, data ? "have" : "have NOT");
2742
                if(data > 1) {
2743
                        JANUS_LOG(LOG_ERR, "[%"SCNu64"] More than one data line? only going to negotiate one...\n", ice_handle->handle_id);
2744
                }
2745
#ifndef HAVE_SCTP
2746
                if(data) {
2747
                        JANUS_LOG(LOG_WARN, "[%"SCNu64"]   -- DataChannels have been negotiated, but support for them has not been compiled...\n", ice_handle->handle_id);
2748
                }
2749
#endif
2750
                /* Are we still cleaning up from a previous media session? */
2751
                if(janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_CLEANING)) {
2752
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Still cleaning up from a previous media session, let's wait a bit...\n", ice_handle->handle_id);
2753
                        gint64 waited = 0;
2754
                        while(janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_CLEANING)) {
2755
                                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Still cleaning up from a previous media session, let's wait a bit...\n", ice_handle->handle_id);
2756
                                g_usleep(100000);
2757
                                waited += 100000;
2758
                                if(waited >= 3*G_USEC_PER_SEC) {
2759
                                        JANUS_LOG(LOG_VERB, "[%"SCNu64"]   -- Waited 3 seconds, that's enough!\n", ice_handle->handle_id);
2760
                                        break;
2761
                                }
2762
                        }
2763
                }
2764
                if(ice_handle->agent == NULL) {
2765
                        /* Process SDP in order to setup ICE locally (this is going to result in an answer from the browser) */
2766
                        if(janus_ice_setup_local(ice_handle, 0, audio, video, data, bundle, rtcpmux, trickle) < 0) {
2767
                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Error setting ICE locally\n", ice_handle->handle_id);
2768
                                janus_sdp_free(parsed_sdp);
2769
                                return NULL;
2770
                        }
2771
                } else {
2772
                        updating = TRUE;
2773
                        JANUS_LOG(LOG_INFO, "[%"SCNu64"] Updating existing session\n", ice_handle->handle_id);
2774
                }
2775
        }
2776
        if(!updating) {
2777
                /* Wait for candidates-done callback */
2778
                while(ice_handle->cdone < ice_handle->streams_num) {
2779
                        if(ice_handle == NULL || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
2780
                                        || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT)) {
2781
                                JANUS_LOG(LOG_WARN, "[%"SCNu64"] Handle detached or PC closed, giving up...!\n", ice_handle ? ice_handle->handle_id : 0);
2782
                                janus_sdp_free(parsed_sdp);
2783
                                return NULL;
2784
                        }
2785
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Waiting for candidates-done callback...\n", ice_handle->handle_id);
2786
                        g_usleep(100000);
2787
                        if(ice_handle->cdone < 0) {
2788
                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Error gathering candidates!\n", ice_handle->handle_id);
2789
                                janus_sdp_free(parsed_sdp);
2790
                                return NULL;
2791
                        }
2792
                }
2793
        }
2794
        /* Anonymize SDP */
2795
        if(janus_sdp_anonymize(parsed_sdp) < 0) {
2796
                /* Invalid SDP */
2797
                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Invalid SDP\n", ice_handle->handle_id);
2798
                janus_sdp_free(parsed_sdp);
2799
                return NULL;
2800
        }
2801
        /* Add our details */
2802
        char *sdp_merged = janus_sdp_merge(ice_handle, parsed_sdp);
2803
        if(sdp_merged == NULL) {
2804
                /* Couldn't merge SDP */
2805
                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Error merging SDP\n", ice_handle->handle_id);
2806
                janus_sdp_free(parsed_sdp);
2807
                return NULL;
2808
        }
2809
        janus_sdp_free(parsed_sdp);
2810
        /* FIXME Any disabled m-line? */
2811
        if(strstr(sdp_merged, "m=audio 0")) {
2812
                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Audio disabled via SDP\n", ice_handle->handle_id);
2813
                if(!janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)
2814
                                || (!video && !data)) {
2815
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"]   -- Marking audio stream as disabled\n", ice_handle->handle_id);
2816
                        janus_ice_stream *stream = g_hash_table_lookup(ice_handle->streams, GUINT_TO_POINTER(ice_handle->audio_id));
2817
                        if(stream)
2818
                                stream->disabled = TRUE;
2819
                }
2820
        }
2821
        if(strstr(sdp_merged, "m=video 0")) {
2822
                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Video disabled via SDP\n", ice_handle->handle_id);
2823
                if(!janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)
2824
                                || (!audio && !data)) {
2825
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"]   -- Marking video stream as disabled\n", ice_handle->handle_id);
2826
                        janus_ice_stream *stream = NULL;
2827
                        if(!janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)) {
2828
                                stream = g_hash_table_lookup(ice_handle->streams, GUINT_TO_POINTER(ice_handle->video_id));
2829
                        } else {
2830
                                gint id = ice_handle->audio_id > 0 ? ice_handle->audio_id : ice_handle->video_id;
2831
                                stream = g_hash_table_lookup(ice_handle->streams, GUINT_TO_POINTER(id));
2832
                        }
2833
                        if(stream)
2834
                                stream->disabled = TRUE;
2835
                }
2836
        }
2837
        if(strstr(sdp_merged, "m=application 0 DTLS/SCTP")) {
2838
                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Data Channel disabled via SDP\n", ice_handle->handle_id);
2839
                if(!janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)
2840
                                || (!audio && !video)) {
2841
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"]   -- Marking data channel stream as disabled\n", ice_handle->handle_id);
2842
                        janus_ice_stream *stream = NULL;
2843
                        if(!janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)) {
2844
                                stream = g_hash_table_lookup(ice_handle->streams, GUINT_TO_POINTER(ice_handle->data_id));
2845
                        } else {
2846
                                gint id = ice_handle->audio_id > 0 ? ice_handle->audio_id : (ice_handle->video_id > 0 ? ice_handle->video_id : ice_handle->data_id);
2847
                                stream = g_hash_table_lookup(ice_handle->streams, GUINT_TO_POINTER(id));
2848
                        }
2849
                        if(stream)
2850
                                stream->disabled = TRUE;
2851
                }
2852
        }
2853

    
2854
        if(!updating) {
2855
                if(offer) {
2856
                        /* We set the flag to wait for an answer before handling trickle candidates */
2857
                        janus_flags_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
2858
                } else {
2859
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Done! Ready to setup remote candidates and send connectivity checks...\n", ice_handle->handle_id);
2860
                        if(janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)) {
2861
                                JANUS_LOG(LOG_VERB, "[%"SCNu64"]   -- bundle is supported by the browser, getting rid of one of the RTP/RTCP components, if any...\n", ice_handle->handle_id);
2862
                                if(audio) {
2863
                                        /* Get rid of video and data, if present */
2864
                                        if(ice_handle->streams && ice_handle->video_stream) {
2865
                                                ice_handle->audio_stream->video_ssrc = ice_handle->video_stream->video_ssrc;
2866
                                                ice_handle->audio_stream->video_ssrc_peer = ice_handle->video_stream->video_ssrc_peer;
2867
                                                ice_handle->audio_stream->video_ssrc_peer_rtx = ice_handle->video_stream->video_ssrc_peer_rtx;
2868
                                                nice_agent_attach_recv(ice_handle->agent, ice_handle->video_stream->stream_id, 1, g_main_loop_get_context (ice_handle->iceloop), NULL, NULL);
2869
                                                if(!janus_ice_is_rtcpmux_forced())
2870
                                                        nice_agent_attach_recv(ice_handle->agent, ice_handle->video_stream->stream_id, 2, g_main_loop_get_context (ice_handle->iceloop), NULL, NULL);
2871
                                                nice_agent_remove_stream(ice_handle->agent, ice_handle->video_stream->stream_id);
2872
                                                janus_ice_stream_free(ice_handle->streams, ice_handle->video_stream);
2873
                                        }
2874
                                        ice_handle->video_stream = NULL;
2875
                                        ice_handle->video_id = 0;
2876
                                        if(ice_handle->streams && ice_handle->data_stream) {
2877
                                                nice_agent_attach_recv(ice_handle->agent, ice_handle->data_stream->stream_id, 1, g_main_loop_get_context (ice_handle->iceloop), NULL, NULL);
2878
                                                nice_agent_remove_stream(ice_handle->agent, ice_handle->data_stream->stream_id);
2879
                                                janus_ice_stream_free(ice_handle->streams, ice_handle->data_stream);
2880
                                        }
2881
                                        ice_handle->data_stream = NULL;
2882
                                        ice_handle->data_id = 0;
2883
                                        if(!video) {
2884
                                                ice_handle->audio_stream->video_ssrc = 0;
2885
                                                ice_handle->audio_stream->video_ssrc_peer = 0;
2886
                                                g_free(ice_handle->audio_stream->video_rtcp_ctx);
2887
                                                ice_handle->audio_stream->video_rtcp_ctx = NULL;
2888
                                        }
2889
                                } else if(video) {
2890
                                        /* Get rid of data, if present */
2891
                                        if(ice_handle->streams && ice_handle->data_stream) {
2892
                                                nice_agent_attach_recv(ice_handle->agent, ice_handle->data_stream->stream_id, 1, g_main_loop_get_context (ice_handle->iceloop), NULL, NULL);
2893
                                                nice_agent_remove_stream(ice_handle->agent, ice_handle->data_stream->stream_id);
2894
                                                janus_ice_stream_free(ice_handle->streams, ice_handle->data_stream);
2895
                                        }
2896
                                        ice_handle->data_stream = NULL;
2897
                                        ice_handle->data_id = 0;
2898
                                }
2899
                        }
2900
                        if(janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_RTCPMUX) && !janus_ice_is_rtcpmux_forced()) {
2901
                                JANUS_LOG(LOG_VERB, "[%"SCNu64"]   -- rtcp-mux is supported by the browser, getting rid of RTCP components, if any...\n", ice_handle->handle_id);
2902
                                if(ice_handle->audio_stream && ice_handle->audio_stream->rtcp_component && ice_handle->audio_stream->components != NULL) {
2903
                                        nice_agent_attach_recv(ice_handle->agent, ice_handle->audio_id, 2, g_main_loop_get_context (ice_handle->iceloop), NULL, NULL);
2904
                                        /* Free the component */
2905
                                        janus_ice_component_free(ice_handle->audio_stream->components, ice_handle->audio_stream->rtcp_component);
2906
                                        ice_handle->audio_stream->rtcp_component = NULL;
2907
                                        /* Create a dummy candidate and enforce it as the one to use for this now unneeded component */
2908
                                        NiceCandidate *c = nice_candidate_new(NICE_CANDIDATE_TYPE_HOST);
2909
                                        c->component_id = 2;
2910
                                        c->stream_id = ice_handle->audio_stream->stream_id;
2911
#ifndef HAVE_LIBNICE_TCP
2912
                                        c->transport = NICE_CANDIDATE_TRANSPORT_UDP;
2913
#endif
2914
                                        strncpy(c->foundation, "1", NICE_CANDIDATE_MAX_FOUNDATION);
2915
                                        c->priority = 1;
2916
                                        nice_address_set_from_string(&c->addr, "127.0.0.1");
2917
                                        nice_address_set_port(&c->addr, janus_ice_get_rtcpmux_blackhole_port());
2918
                                        c->username = g_strdup(ice_handle->audio_stream->ruser);
2919
                                        c->password = g_strdup(ice_handle->audio_stream->rpass);
2920
                                        if(!nice_agent_set_selected_remote_candidate(ice_handle->agent, ice_handle->audio_stream->stream_id, 2, c)) {
2921
                                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Error forcing dummy candidate on RTCP component of stream %d\n", ice_handle->handle_id, ice_handle->audio_stream->stream_id);
2922
                                                nice_candidate_free(c);
2923
                                        }
2924
                                }
2925
                                if(ice_handle->video_stream && ice_handle->video_stream->rtcp_component && ice_handle->video_stream->components != NULL) {
2926
                                        nice_agent_attach_recv(ice_handle->agent, ice_handle->video_id, 2, g_main_loop_get_context (ice_handle->iceloop), NULL, NULL);
2927
                                        /* Free the component */
2928
                                        janus_ice_component_free(ice_handle->video_stream->components, ice_handle->video_stream->rtcp_component);
2929
                                        ice_handle->video_stream->rtcp_component = NULL;
2930
                                        /* Create a dummy candidate and enforce it as the one to use for this now unneeded component */
2931
                                        NiceCandidate *c = nice_candidate_new(NICE_CANDIDATE_TYPE_HOST);
2932
                                        c->component_id = 2;
2933
                                        c->stream_id = ice_handle->video_stream->stream_id;
2934
#ifndef HAVE_LIBNICE_TCP
2935
                                        c->transport = NICE_CANDIDATE_TRANSPORT_UDP;
2936
#endif
2937
                                        strncpy(c->foundation, "1", NICE_CANDIDATE_MAX_FOUNDATION);
2938
                                        c->priority = 1;
2939
                                        nice_address_set_from_string(&c->addr, "127.0.0.1");
2940
                                        nice_address_set_port(&c->addr, janus_ice_get_rtcpmux_blackhole_port());
2941
                                        c->username = g_strdup(ice_handle->video_stream->ruser);
2942
                                        c->password = g_strdup(ice_handle->video_stream->rpass);
2943
                                        if(!nice_agent_set_selected_remote_candidate(ice_handle->agent, ice_handle->video_stream->stream_id, 2, c)) {
2944
                                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Error forcing dummy candidate on RTCP component of stream %d\n", ice_handle->handle_id, ice_handle->video_stream->stream_id);
2945
                                                nice_candidate_free(c);
2946
                                        }
2947
                                }
2948
                        }
2949
                        janus_mutex_lock(&ice_handle->mutex);
2950
                        /* We got our answer */
2951
                        janus_flags_clear(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
2952
                        /* Any pending trickles? */
2953
                        if(ice_handle->pending_trickles) {
2954
                                JANUS_LOG(LOG_VERB, "[%"SCNu64"]   -- Processing %d pending trickle candidates\n", ice_handle->handle_id, g_list_length(ice_handle->pending_trickles));
2955
                                GList *temp = NULL;
2956
                                while(ice_handle->pending_trickles) {
2957
                                        temp = g_list_first(ice_handle->pending_trickles);
2958
                                        ice_handle->pending_trickles = g_list_remove_link(ice_handle->pending_trickles, temp);
2959
                                        janus_ice_trickle *trickle = (janus_ice_trickle *)temp->data;
2960
                                        g_list_free(temp);
2961
                                        if(trickle == NULL)
2962
                                                continue;
2963
                                        if((janus_get_monotonic_time() - trickle->received) > 45*G_USEC_PER_SEC) {
2964
                                                /* FIXME Candidate is too old, discard it */
2965
                                                janus_ice_trickle_destroy(trickle);
2966
                                                /* FIXME We should report that */
2967
                                                continue;
2968
                                        }
2969
                                        json_t *candidate = trickle->candidate;
2970
                                        if(candidate == NULL) {
2971
                                                janus_ice_trickle_destroy(trickle);
2972
                                                continue;
2973
                                        }
2974
                                        if(json_is_object(candidate)) {
2975
                                                /* We got a single candidate */
2976
                                                int error = 0;
2977
                                                const char *error_string = NULL;
2978
                                                if((error = janus_ice_trickle_parse(ice_handle, candidate, &error_string)) != 0) {
2979
                                                        /* FIXME We should report the error parsing the trickle candidate */
2980
                                                }
2981
                                        } else if(json_is_array(candidate)) {
2982
                                                /* We got multiple candidates in an array */
2983
                                                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Got multiple candidates (%zu)\n", ice_handle->handle_id, json_array_size(candidate));
2984
                                                if(json_array_size(candidate) > 0) {
2985
                                                        /* Handle remote candidates */
2986
                                                        size_t i = 0;
2987
                                                        for(i=0; i<json_array_size(candidate); i++) {
2988
                                                                json_t *c = json_array_get(candidate, i);
2989
                                                                /* FIXME We don't care if any trickle fails to parse */
2990
                                                                janus_ice_trickle_parse(ice_handle, c, NULL);
2991
                                                        }
2992
                                                }
2993
                                        }
2994
                                        /* Done, free candidate */
2995
                                        janus_ice_trickle_destroy(trickle);
2996
                                }
2997
                        }
2998
                        /* This was an answer, check if it's time to start ICE */
2999
                        if(janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_TRICKLE) &&
3000
                                        !janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALL_TRICKLES)) {
3001
                                JANUS_LOG(LOG_VERB, "[%"SCNu64"]   -- ICE Trickling is supported by the browser, waiting for remote candidates...\n", ice_handle->handle_id);
3002
                                janus_flags_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_START);
3003
                        } else {
3004
                                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Done! Sending connectivity checks...\n", ice_handle->handle_id);
3005
                                if(ice_handle->audio_id > 0) {
3006
                                        janus_ice_setup_remote_candidates(ice_handle, ice_handle->audio_id, 1);
3007
                                        if(!janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_RTCPMUX))        /* http://tools.ietf.org/html/rfc5761#section-5.1.3 */
3008
                                                janus_ice_setup_remote_candidates(ice_handle, ice_handle->audio_id, 2);
3009
                                }
3010
                                if(ice_handle->video_id > 0) {
3011
                                        janus_ice_setup_remote_candidates(ice_handle, ice_handle->video_id, 1);
3012
                                        if(!janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_RTCPMUX))        /* http://tools.ietf.org/html/rfc5761#section-5.1.3 */
3013
                                                janus_ice_setup_remote_candidates(ice_handle, ice_handle->video_id, 2);
3014
                                }
3015
                                if(ice_handle->data_id > 0) {
3016
                                        janus_ice_setup_remote_candidates(ice_handle, ice_handle->data_id, 1);
3017
                                }
3018
                        }
3019
                        janus_mutex_unlock(&ice_handle->mutex);
3020
                }
3021
        }
3022

    
3023
        /* Prepare JSON event */
3024
        json_t *jsep = json_object();
3025
        json_object_set_new(jsep, "type", json_string(sdp_type));
3026
        json_object_set_new(jsep, "sdp", json_string(sdp_merged));
3027
        ice_handle->local_sdp = sdp_merged;
3028
        return jsep;
3029
}
3030

    
3031
void janus_plugin_relay_rtp(janus_plugin_session *plugin_session, int video, char *buf, int len) {
3032
        if((plugin_session < (janus_plugin_session *)0x1000) || plugin_session->stopped || buf == NULL || len < 1)
3033
                return;
3034
        janus_ice_handle *handle = (janus_ice_handle *)plugin_session->gateway_handle;
3035
        if(!handle || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
3036
                        || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
3037
                return;
3038
        janus_ice_relay_rtp(handle, video, buf, len);
3039
}
3040

    
3041
void janus_plugin_relay_rtcp(janus_plugin_session *plugin_session, int video, char *buf, int len) {
3042
        if((plugin_session < (janus_plugin_session *)0x1000) || plugin_session->stopped || buf == NULL || len < 1)
3043
                return;
3044
        janus_ice_handle *handle = (janus_ice_handle *)plugin_session->gateway_handle;
3045
        if(!handle || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
3046
                        || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
3047
                return;
3048
        janus_ice_relay_rtcp(handle, video, buf, len);
3049
}
3050

    
3051
void janus_plugin_relay_data(janus_plugin_session *plugin_session, char *buf, int len) {
3052
        if((plugin_session < (janus_plugin_session *)0x1000) || plugin_session->stopped || buf == NULL || len < 1)
3053
                return;
3054
        janus_ice_handle *handle = (janus_ice_handle *)plugin_session->gateway_handle;
3055
        if(!handle || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
3056
                        || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
3057
                return;
3058
#ifdef HAVE_SCTP
3059
        janus_ice_relay_data(handle, buf, len);
3060
#else
3061
        JANUS_LOG(LOG_WARN, "Asked to relay data, but Data Channels support has not been compiled...\n");
3062
#endif
3063
}
3064

    
3065
void janus_plugin_close_pc(janus_plugin_session *plugin_session) {
3066
        /* A plugin asked to get rid of a PeerConnection */
3067
        if((plugin_session < (janus_plugin_session *)0x1000) || !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped)
3068
                return;
3069
        janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
3070
        if(!ice_handle)
3071
                return;
3072
        if(janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
3073
                        || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
3074
                return;
3075
        janus_session *session = (janus_session *)ice_handle->session;
3076
        if(!session)
3077
                return;
3078

    
3079
        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Plugin asked to hangup PeerConnection: sending alert\n", ice_handle->handle_id);
3080
        /* Send an alert on all the DTLS connections */
3081
        janus_ice_webrtc_hangup(ice_handle, "Close PC");
3082
}
3083

    
3084
void janus_plugin_end_session(janus_plugin_session *plugin_session) {
3085
        /* A plugin asked to get rid of a handle */
3086
        if((plugin_session < (janus_plugin_session *)0x1000) || !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped)
3087
                return;
3088
        janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
3089
        if(!ice_handle)
3090
                return;
3091
        janus_session *session = (janus_session *)ice_handle->session;
3092
        if(!session)
3093
                return;
3094
        /* Destroy the handle */
3095
        janus_ice_handle_destroy(session, ice_handle->handle_id);
3096
        janus_mutex_lock(&session->mutex);
3097
        g_hash_table_remove(session->ice_handles, &ice_handle->handle_id);
3098
        janus_mutex_unlock(&session->mutex);
3099
}
3100

    
3101
void janus_plugin_notify_event(janus_plugin *plugin, janus_plugin_session *plugin_session, json_t *event) {
3102
        /* A plugin asked to notify an event to the handlers */
3103
        if(!plugin || !event || !json_is_object(event))
3104
                return;
3105
        guint64 session_id = 0, handle_id = 0;
3106
        if(plugin_session != NULL) {
3107
                if((plugin_session < (janus_plugin_session *)0x1000) || !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped) {
3108
                        json_decref(event);
3109
                        return;
3110
                }
3111
                janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
3112
                if(!ice_handle) {
3113
                        json_decref(event);
3114
                        return;
3115
                }
3116
                handle_id = ice_handle->handle_id;
3117
                janus_session *session = (janus_session *)ice_handle->session;
3118
                if(!session) {
3119
                        json_decref(event);
3120
                        return;
3121
                }
3122
                session_id = session->session_id;
3123
        }
3124
        /* Notify event handlers */
3125
        if(janus_events_is_enabled()) {
3126
                janus_events_notify_handlers(JANUS_EVENT_TYPE_PLUGIN,
3127
                        session_id, handle_id, plugin->get_package(), event);
3128
        } else {
3129
                json_decref(event);
3130
        }
3131
}
3132

    
3133

    
3134
/* Main */
3135
gint main(int argc, char *argv[])
3136
{
3137
        /* Core dumps may be disallowed by parent of this process; change that */
3138
        struct rlimit core_limits;
3139
        core_limits.rlim_cur = core_limits.rlim_max = RLIM_INFINITY;
3140
        setrlimit(RLIMIT_CORE, &core_limits);
3141

    
3142
        g_print("Janus commit: %s\n", janus_build_git_sha);
3143
        g_print("Compiled on:  %s\n\n", janus_build_git_time);
3144

    
3145
        struct gengetopt_args_info args_info;
3146
        /* Let's call our cmdline parser */
3147
        if(cmdline_parser(argc, argv, &args_info) != 0)
3148
                exit(1);
3149

    
3150
        /* Any configuration to open? */
3151
        if(args_info.config_given) {
3152
                config_file = g_strdup(args_info.config_arg);
3153
        }
3154
        if(args_info.configs_folder_given) {
3155
                configs_folder = g_strdup(args_info.configs_folder_arg);
3156
        } else {
3157
                configs_folder = g_strdup (CONFDIR);
3158
        }
3159
        if(config_file == NULL) {
3160
                char file[255];
3161
                g_snprintf(file, 255, "%s/janus.cfg", configs_folder);
3162
                config_file = g_strdup(file);
3163
        }
3164
        if((config = janus_config_parse(config_file)) == NULL) {
3165
                if(args_info.config_given) {
3166
                        /* We only give up if the configuration file was explicitly provided */
3167
                        g_print("Error reading configuration from %s\n", config_file);
3168
                        exit(1);
3169
                }
3170
                g_print("Error reading/parsing the configuration file, going on with the defaults and the command line arguments\n");
3171
                config = janus_config_create("janus.cfg");
3172
                if(config == NULL) {
3173
                        /* If we can't even create an empty configuration, something's definitely wrong */
3174
                        exit(1);
3175
                }
3176
        }
3177

    
3178
        /* Check if we need to log to console and/or file */
3179
        gboolean use_stdout = TRUE;
3180
        if(args_info.disable_stdout_given) {
3181
                use_stdout = FALSE;
3182
                janus_config_add_item(config, "general", "log_to_stdout", "no");
3183
        } else {
3184
                /* Check if the configuration file is saying anything about this */
3185
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "log_to_stdout");
3186
                if(item && item->value && !janus_is_true(item->value))
3187
                        use_stdout = FALSE;
3188
        }
3189
        const char *logfile = NULL;
3190
        if(args_info.log_file_given) {
3191
                logfile = args_info.log_file_arg;
3192
                janus_config_add_item(config, "general", "log_to_file", "no");
3193
        } else {
3194
                /* Check if the configuration file is saying anything about this */
3195
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "log_to_file");
3196
                if(item && item->value)
3197
                        logfile = item->value;
3198
        }
3199

    
3200
        /* Check if we're going to daemonize Janus */
3201
        if(args_info.daemon_given) {
3202
                daemonize = TRUE;
3203
                janus_config_add_item(config, "general", "daemonize", "yes");
3204
        } else {
3205
                /* Check if the configuration file is saying anything about this */
3206
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "daemonize");
3207
                if(item && item->value && janus_is_true(item->value))
3208
                        daemonize = TRUE;
3209
        }
3210
        /* If we're going to daemonize, make sure logging to stdout is disabled and a log file has been specified */
3211
        if(daemonize && use_stdout) {
3212
                use_stdout = FALSE;
3213
        }
3214
        if(daemonize && logfile == NULL) {
3215
                g_print("Running Janus as a daemon but no log file provided, giving up...\n");
3216
                exit(1);
3217
        }
3218
        /* Daemonize now, if we need to */
3219
        if(daemonize) {
3220
                g_print("Running Janus as a daemon\n");
3221

    
3222
                /* Create a pipe for parent<->child communication during the startup phase */
3223
                if(pipe(pipefd) == -1) {
3224
                        g_print("pipe error!\n");
3225
                        exit(1);
3226
                }
3227

    
3228
                /* Fork off the parent process */
3229
                pid_t pid = fork();
3230
                if(pid < 0) {
3231
                        g_print("Fork error!\n");
3232
                        exit(1);
3233
                }
3234
                if(pid > 0) {
3235
                        /* Ok, we're the parent: let's wait for the child to tell us everything started fine */
3236
                        close(pipefd[1]);
3237
                        int code = -1;
3238
                        struct pollfd pollfds;
3239

    
3240
                        while(code < 0) {
3241
                                pollfds.fd = pipefd[0];
3242
                                pollfds.events = POLLIN;
3243
                                int res = poll(&pollfds, 1, -1);
3244
                                if(res < 0)
3245
                                        break;
3246
                                if(res == 0)
3247
                                        continue;
3248
                                if(pollfds.revents & POLLERR || pollfds.revents & POLLHUP)
3249
                                        break;
3250
                                if(pollfds.revents & POLLIN) {
3251
                                        res = read(pipefd[0], &code, sizeof(int));
3252
                                        break;
3253
                                }
3254
                        }
3255
                        if(code < 0)
3256
                                code = 1;
3257

    
3258
                        /* Leave the parent and return the exit code we received from the child */
3259
                        if(code)
3260
                                g_print("Error launching Janus (error code %d), check the logs for more details\n", code);
3261
                        exit(code);
3262
                }
3263
                /* Change the file mode mask */
3264
                umask(0);
3265

    
3266
                /* Create a new SID for the child process */
3267
                pid_t sid = setsid();
3268
                if(sid < 0) {
3269
                        g_print("Error setting SID!\n");
3270
                        exit(1);
3271
                }
3272
                /* Change the current working directory */
3273
                if((chdir("/")) < 0) {
3274
                        g_print("Error changing the current working directory!\n");
3275
                        exit(1);
3276
                }
3277
                /* We close stdin/stdout/stderr when initializing the logger */
3278
        }
3279

    
3280
        /* Initialize logger */
3281
        if(janus_log_init(daemonize, use_stdout, logfile) < 0)
3282
                exit(1);
3283

    
3284
        JANUS_PRINT("---------------------------------------------------\n");
3285
        JANUS_PRINT("  Starting Meetecho Janus (WebRTC Gateway) v%s\n", JANUS_VERSION_STRING);
3286
        JANUS_PRINT("---------------------------------------------------\n\n");
3287

    
3288
        /* Handle SIGINT (CTRL-C), SIGTERM (from service managers) */
3289
        signal(SIGINT, janus_handle_signal);
3290
        signal(SIGTERM, janus_handle_signal);
3291
        atexit(janus_termination_handler);
3292

    
3293
        /* Setup Glib */
3294
#if !GLIB_CHECK_VERSION(2, 36, 0)
3295
        g_type_init();
3296
#endif
3297

    
3298
        /* Logging level: default is info and no timestamps */
3299
        janus_log_level = LOG_INFO;
3300
        janus_log_timestamps = FALSE;
3301
        janus_log_colors = TRUE;
3302
        if(args_info.debug_level_given) {
3303
                if(args_info.debug_level_arg < LOG_NONE)
3304
                        args_info.debug_level_arg = 0;
3305
                else if(args_info.debug_level_arg > LOG_MAX)
3306
                        args_info.debug_level_arg = LOG_MAX;
3307
                janus_log_level = args_info.debug_level_arg;
3308
        }
3309

    
3310
        /* Any PID we need to create? */
3311
        const char *pidfile = NULL;
3312
        if(args_info.pid_file_given) {
3313
                pidfile = args_info.pid_file_arg;
3314
                janus_config_add_item(config, "general", "pid_file", pidfile);
3315
        } else {
3316
                /* Check if the configuration file is saying anything about this */
3317
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "pid_file");
3318
                if(item && item->value)
3319
                        pidfile = item->value;
3320
        }
3321
        if(janus_pidfile_create(pidfile) < 0)
3322
                exit(1);
3323

    
3324
        /* Proceed with the rest of the configuration */
3325
        janus_config_print(config);
3326
        if(args_info.debug_level_given) {
3327
                char debug[5];
3328
                g_snprintf(debug, 5, "%d", args_info.debug_level_arg);
3329
                janus_config_add_item(config, "general", "debug_level", debug);
3330
        } else {
3331
                /* No command line directive on logging, try the configuration file */
3332
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "debug_level");
3333
                if(item && item->value) {
3334
                        int temp_level = atoi(item->value);
3335
                        if(temp_level == 0 && strcmp(item->value, "0")) {
3336
                                JANUS_PRINT("Invalid debug level %s (configuration), using default (info=4)\n", item->value);
3337
                        } else {
3338
                                janus_log_level = temp_level;
3339
                                if(janus_log_level < LOG_NONE)
3340
                                        janus_log_level = 0;
3341
                                else if(janus_log_level > LOG_MAX)
3342
                                        janus_log_level = LOG_MAX;
3343
                        }
3344
                }
3345
        }
3346
        /* Any command line argument that should overwrite the configuration? */
3347
        JANUS_PRINT("Checking command line arguments...\n");
3348
        if(args_info.debug_timestamps_given) {
3349
                janus_config_add_item(config, "general", "debug_timestamps", "yes");
3350
        }
3351
        if(args_info.disable_colors_given) {
3352
                janus_config_add_item(config, "general", "debug_colors", "no");
3353
        }
3354
        if(args_info.server_name_given) {
3355
                janus_config_add_item(config, "general", "server_name", args_info.server_name_arg);
3356
        }
3357
        if(args_info.session_timeout_given) {
3358
                char st[20];
3359
                g_snprintf(st, 20, "%d", args_info.session_timeout_arg);
3360
                janus_config_add_item(config, "general", "session_timeout", st);
3361
        }
3362
         if(args_info.interface_given) {
3363
                janus_config_add_item(config, "general", "interface", args_info.interface_arg);
3364
        }
3365
        if(args_info.configs_folder_given) {
3366
                janus_config_add_item(config, "general", "configs_folder", args_info.configs_folder_arg);
3367
        }
3368
        if(args_info.plugins_folder_given) {
3369
                janus_config_add_item(config, "general", "plugins_folder", args_info.plugins_folder_arg);
3370
        }
3371
        if(args_info.apisecret_given) {
3372
                janus_config_add_item(config, "general", "api_secret", args_info.apisecret_arg);
3373
        }
3374
        if(args_info.token_auth_given) {
3375
                janus_config_add_item(config, "general", "token_auth", "yes");
3376
        }
3377
        if(args_info.cert_pem_given) {
3378
                janus_config_add_item(config, "certificates", "cert_pem", args_info.cert_pem_arg);
3379
        }
3380
        if(args_info.cert_key_given) {
3381
                janus_config_add_item(config, "certificates", "cert_key", args_info.cert_key_arg);
3382
        }
3383
        if(args_info.stun_server_given) {
3384
                /* Split in server and port (if port missing, use 3478 as default) */
3385
                char *stunport = strrchr(args_info.stun_server_arg, ':');
3386
                if(stunport != NULL) {
3387
                        *stunport = '\0';
3388
                        stunport++;
3389
                        janus_config_add_item(config, "nat", "stun_server", args_info.stun_server_arg);
3390
                        janus_config_add_item(config, "nat", "stun_port", stunport);
3391
                } else {
3392
                        janus_config_add_item(config, "nat", "stun_server", args_info.stun_server_arg);
3393
                        janus_config_add_item(config, "nat", "stun_port", "3478");
3394
                }
3395
        }
3396
        if(args_info.nat_1_1_given) {
3397
                janus_config_add_item(config, "nat", "nat_1_1_mapping", args_info.nat_1_1_arg);
3398
        }
3399
        if(args_info.ice_enforce_list_given) {
3400
                janus_config_add_item(config, "nat", "ice_enforce_list", args_info.ice_enforce_list_arg);
3401
        }
3402
        if(args_info.ice_ignore_list_given) {
3403
                janus_config_add_item(config, "nat", "ice_ignore_list", args_info.ice_ignore_list_arg);
3404
        }
3405
        if(args_info.libnice_debug_given) {
3406
                janus_config_add_item(config, "nat", "nice_debug", "true");
3407
        }
3408
        if(args_info.ice_lite_given) {
3409
                janus_config_add_item(config, "nat", "ice_lite", "true");
3410
        }
3411
        if(args_info.ice_tcp_given) {
3412
                janus_config_add_item(config, "nat", "ice_tcp", "true");
3413
        }
3414
        if(args_info.ipv6_candidates_given) {
3415
                janus_config_add_item(config, "media", "ipv6", "true");
3416
        }
3417
        if(args_info.force_bundle_given) {
3418
                janus_config_add_item(config, "media", "force-bundle", "true");
3419
        }
3420
        if(args_info.force_rtcp_mux_given) {
3421
                janus_config_add_item(config, "media", "force-rtcp-mux", "true");
3422
        }
3423
        if(args_info.max_nack_queue_given) {
3424
                char mnq[20];
3425
                g_snprintf(mnq, 20, "%d", args_info.max_nack_queue_arg);
3426
                janus_config_add_item(config, "media", "max_nack_queue", mnq);
3427
        }
3428
        if(args_info.no_media_timer_given) {
3429
                char nmt[20];
3430
                g_snprintf(nmt, 20, "%d", args_info.no_media_timer_arg);
3431
                janus_config_add_item(config, "media", "no_media_timer", nmt);
3432
        }
3433
        if(args_info.rtp_port_range_given) {
3434
                janus_config_add_item(config, "media", "rtp_port_range", args_info.rtp_port_range_arg);
3435
        }
3436
        if(args_info.event_handlers_given) {
3437
                janus_config_add_item(config, "events", "broadcast", "yes");
3438
        }
3439
        janus_config_print(config);
3440

    
3441
        /* Logging/debugging */
3442
        JANUS_PRINT("Debug/log level is %d\n", janus_log_level);
3443
        janus_config_item *item = janus_config_get_item_drilldown(config, "general", "debug_timestamps");
3444
        if(item && item->value)
3445
                janus_log_timestamps = janus_is_true(item->value);
3446
        JANUS_PRINT("Debug/log timestamps are %s\n", janus_log_timestamps ? "enabled" : "disabled");
3447
        item = janus_config_get_item_drilldown(config, "general", "debug_colors");
3448
        if(item && item->value)
3449
                janus_log_colors = janus_is_true(item->value);
3450
        JANUS_PRINT("Debug/log colors are %s\n", janus_log_colors ? "enabled" : "disabled");
3451

    
3452
        /* Any IP/interface to enforce/ignore? */
3453
        item = janus_config_get_item_drilldown(config, "nat", "ice_enforce_list");
3454
        if(item && item->value) {
3455
                gchar **list = g_strsplit(item->value, ",", -1);
3456
                gchar *index = list[0];
3457
                if(index != NULL) {
3458
                        int i=0;
3459
                        while(index != NULL) {
3460
                                if(strlen(index) > 0) {
3461
                                        JANUS_LOG(LOG_INFO, "Adding '%s' to the ICE enforce list...\n", index);
3462
                                        janus_ice_enforce_interface(g_strdup(index));
3463
                                }
3464
                                i++;
3465
                                index = list[i];
3466
                        }
3467
                }
3468
                g_clear_pointer(&list, g_strfreev);
3469
        }
3470
        item = janus_config_get_item_drilldown(config, "nat", "ice_ignore_list");
3471
        if(item && item->value) {
3472
                gchar **list = g_strsplit(item->value, ",", -1);
3473
                gchar *index = list[0];
3474
                if(index != NULL) {
3475
                        int i=0;
3476
                        while(index != NULL) {
3477
                                if(strlen(index) > 0) {
3478
                                        JANUS_LOG(LOG_INFO, "Adding '%s' to the ICE ignore list...\n", index);
3479
                                        janus_ice_ignore_interface(g_strdup(index));
3480
                                }
3481
                                i++;
3482
                                index = list[i];
3483
                        }
3484
                }
3485
                g_clear_pointer(&list, g_strfreev);
3486
        }
3487
        /* What is the local IP? */
3488
        JANUS_LOG(LOG_VERB, "Selecting local IP address...\n");
3489
        item = janus_config_get_item_drilldown(config, "general", "interface");
3490
        if(item && item->value) {
3491
                JANUS_LOG(LOG_VERB, "  -- Will try to use %s\n", item->value);
3492
                /* Verify that the address is valid */
3493
                struct ifaddrs *ifas = NULL;
3494
                janus_network_address iface;
3495
                janus_network_address_string_buffer ibuf;
3496
                if(getifaddrs(&ifas) || ifas == NULL) {
3497
                        JANUS_LOG(LOG_ERR, "Unable to acquire list of network devices/interfaces; some configurations may not work as expected...\n");
3498
                } else {
3499
                        if(janus_network_lookup_interface(ifas, item->value, &iface) != 0) {
3500
                                JANUS_LOG(LOG_WARN, "Error setting local IP address to %s, falling back to detecting IP address...\n", item->value);
3501
                        } else {
3502
                                if(janus_network_address_to_string_buffer(&iface, &ibuf) != 0 || janus_network_address_string_buffer_is_null(&ibuf)) {
3503
                                        JANUS_LOG(LOG_WARN, "Error getting local IP address from %s, falling back to detecting IP address...\n", item->value);
3504
                                } else {
3505
                                        local_ip = g_strdup(janus_network_address_string_from_buffer(&ibuf));
3506
                                }
3507
                        }
3508
                }
3509
        }
3510
        if(local_ip == NULL) {
3511
                local_ip = janus_network_detect_local_ip_as_string(janus_network_query_options_any_ip);
3512
                if(local_ip == NULL) {
3513
                        JANUS_LOG(LOG_WARN, "Couldn't find any address! using 127.0.0.1 as the local IP... (which is NOT going to work out of your machine)\n");
3514
                        local_ip = g_strdup("127.0.0.1");
3515
                }
3516
        }
3517
        JANUS_LOG(LOG_INFO, "Using %s as local IP...\n", local_ip);
3518

    
3519
        /* Was a custom instance name provided? */
3520
        item = janus_config_get_item_drilldown(config, "general", "server_name");
3521
        if(item && item->value) {
3522
                server_name = g_strdup(item->value);
3523
        }
3524

    
3525
        /* Check if a custom session timeout value was specified */
3526
        item = janus_config_get_item_drilldown(config, "general", "session_timeout");
3527
        if(item && item->value) {
3528
                int st = atoi(item->value);
3529
                if(st < 0) {
3530
                        JANUS_LOG(LOG_WARN, "Ignoring session_timeout value as it's not a positive integer\n");
3531
                } else {
3532
                        if(st == 0) {
3533
                                JANUS_LOG(LOG_WARN, "Session timeouts have been disabled (note, may result in orphaned sessions)\n");
3534
                        }
3535
                        session_timeout = st;
3536
                }
3537
        }
3538

    
3539
        /* Is there any API secret to consider? */
3540
        api_secret = NULL;
3541
        item = janus_config_get_item_drilldown(config, "general", "api_secret");
3542
        if(item && item->value) {
3543
                api_secret = g_strdup(item->value);
3544
        }
3545
        /* Is there any API secret to consider? */
3546
        admin_api_secret = NULL;
3547
        item = janus_config_get_item_drilldown(config, "general", "admin_secret");
3548
        if(item && item->value) {
3549
                admin_api_secret = g_strdup(item->value);
3550
        }
3551
        /* Also check if the token based authentication mechanism needs to be enabled */
3552
        item = janus_config_get_item_drilldown(config, "general", "token_auth");
3553
        janus_auth_init(item && item->value && janus_is_true(item->value));
3554

    
3555
        /* Initialize the recorder code */
3556
        item = janus_config_get_item_drilldown(config, "general", "recordings_tmp_ext");
3557
        if(item && item->value) {
3558
                janus_recorder_init(TRUE, item->value);
3559
        } else {
3560
                janus_recorder_init(FALSE, NULL);
3561
        }
3562

    
3563
        /* Setup ICE stuff (e.g., checking if the provided STUN server is correct) */
3564
        char *stun_server = NULL, *turn_server = NULL;
3565
        uint16_t stun_port = 0, turn_port = 0;
3566
        char *turn_type = NULL, *turn_user = NULL, *turn_pwd = NULL;
3567
        char *turn_rest_api = NULL, *turn_rest_api_key = NULL;
3568
#ifdef HAVE_LIBCURL
3569
        char *turn_rest_api_method = NULL;
3570
#endif
3571
        const char *nat_1_1_mapping = NULL;
3572
        uint16_t rtp_min_port = 0, rtp_max_port = 0;
3573
        gboolean ice_lite = FALSE, ice_tcp = FALSE, ipv6 = FALSE;
3574
        item = janus_config_get_item_drilldown(config, "media", "ipv6");
3575
        ipv6 = (item && item->value) ? janus_is_true(item->value) : FALSE;
3576
        item = janus_config_get_item_drilldown(config, "media", "rtp_port_range");
3577
        if(item && item->value) {
3578
                /* Split in min and max port */
3579
                char *maxport = strrchr(item->value, '-');
3580
                if(maxport != NULL) {
3581
                        *maxport = '\0';
3582
                        maxport++;
3583
                        rtp_min_port = atoi(item->value);
3584
                        rtp_max_port = atoi(maxport);
3585
                        maxport--;
3586
                        *maxport = '-';
3587
                }
3588
                if(rtp_min_port > rtp_max_port) {
3589
                        int temp_port = rtp_min_port;
3590
                        rtp_min_port = rtp_max_port;
3591
                        rtp_max_port = temp_port;
3592
                }
3593
                if(rtp_max_port == 0)
3594
                        rtp_max_port = 65535;
3595
                JANUS_LOG(LOG_INFO, "RTP port range: %u -- %u\n", rtp_min_port, rtp_max_port);
3596
        }
3597
        /* Check if we need to enable the ICE Lite mode */
3598
        item = janus_config_get_item_drilldown(config, "nat", "ice_lite");
3599
        ice_lite = (item && item->value) ? janus_is_true(item->value) : FALSE;
3600
        /* Check if we need to enable ICE-TCP support (warning: still broken, for debugging only) */
3601
        item = janus_config_get_item_drilldown(config, "nat", "ice_tcp");
3602
        ice_tcp = (item && item->value) ? janus_is_true(item->value) : FALSE;
3603
        /* Any STUN server to use in Janus? */
3604
        item = janus_config_get_item_drilldown(config, "nat", "stun_server");
3605
        if(item && item->value)
3606
                stun_server = (char *)item->value;
3607
        item = janus_config_get_item_drilldown(config, "nat", "stun_port");
3608
        if(item && item->value)
3609
                stun_port = atoi(item->value);
3610
        /* Any 1:1 NAT mapping to take into account? */
3611
        item = janus_config_get_item_drilldown(config, "nat", "nat_1_1_mapping");
3612
        if(item && item->value) {
3613
                JANUS_LOG(LOG_VERB, "Using nat_1_1_mapping for public ip - %s\n", item->value);
3614
                if(!janus_network_string_is_valid_address(janus_network_query_options_any_ip, item->value)) {
3615
                        JANUS_LOG(LOG_WARN, "Invalid nat_1_1_mapping address %s, disabling...\n", item->value);
3616
                } else {
3617
                        nat_1_1_mapping = item->value;
3618
                        janus_set_public_ip(item->value);
3619
                        janus_ice_enable_nat_1_1();
3620
                }
3621
        }
3622
        /* Any TURN server to use in Janus? */
3623
        item = janus_config_get_item_drilldown(config, "nat", "turn_server");
3624
        if(item && item->value)
3625
                turn_server = (char *)item->value;
3626
        item = janus_config_get_item_drilldown(config, "nat", "turn_port");
3627
        if(item && item->value)
3628
                turn_port = atoi(item->value);
3629
        item = janus_config_get_item_drilldown(config, "nat", "turn_type");
3630
        if(item && item->value)
3631
                turn_type = (char *)item->value;
3632
        item = janus_config_get_item_drilldown(config, "nat", "turn_user");
3633
        if(item && item->value)
3634
                turn_user = (char *)item->value;
3635
        item = janus_config_get_item_drilldown(config, "nat", "turn_pwd");
3636
        if(item && item->value)
3637
                turn_pwd = (char *)item->value;
3638
        /* Check if there's any TURN REST API backend to use */
3639
        item = janus_config_get_item_drilldown(config, "nat", "turn_rest_api");
3640
        if(item && item->value)
3641
                turn_rest_api = (char *)item->value;
3642
        item = janus_config_get_item_drilldown(config, "nat", "turn_rest_api_key");
3643
        if(item && item->value)
3644
                turn_rest_api_key = (char *)item->value;
3645
#ifdef HAVE_LIBCURL
3646
        item = janus_config_get_item_drilldown(config, "nat", "turn_rest_api_method");
3647
        if(item && item->value)
3648
                turn_rest_api_method = (char *)item->value;
3649
#endif
3650
        /* Initialize the ICE stack now */
3651
        janus_ice_init(ice_lite, ice_tcp, ipv6, rtp_min_port, rtp_max_port);
3652
        if(janus_ice_set_stun_server(stun_server, stun_port) < 0) {
3653
                JANUS_LOG(LOG_FATAL, "Invalid STUN address %s:%u\n", stun_server, stun_port);
3654
                exit(1);
3655
        }
3656
        if(janus_ice_set_turn_server(turn_server, turn_port, turn_type, turn_user, turn_pwd) < 0) {
3657
                JANUS_LOG(LOG_FATAL, "Invalid TURN address %s:%u\n", turn_server, turn_port);
3658
                exit(1);
3659
        }
3660
#ifndef HAVE_LIBCURL
3661
        if(turn_rest_api != NULL || turn_rest_api_key != NULL) {
3662
                JANUS_LOG(LOG_WARN, "A TURN REST API backend specified in the settings, but libcurl support has not been built\n");
3663
        }
3664
#else
3665
        if(janus_ice_set_turn_rest_api(turn_rest_api, turn_rest_api_key, turn_rest_api_method) < 0) {
3666
                JANUS_LOG(LOG_FATAL, "Invalid TURN REST API configuration: %s (%s, %s)\n", turn_rest_api, turn_rest_api_key, turn_rest_api_method);
3667
                exit(1);
3668
        }
3669
#endif
3670
        item = janus_config_get_item_drilldown(config, "nat", "nice_debug");
3671
        if(item && item->value && janus_is_true(item->value)) {
3672
                /* Enable libnice debugging */
3673
                janus_ice_debugging_enable();
3674
        }
3675
        if(stun_server == NULL && turn_server == NULL) {
3676
                /* No STUN and TURN server provided for Janus: make sure it isn't on a private address */
3677
                gboolean private_address = FALSE;
3678
                const char *test_ip = nat_1_1_mapping ? nat_1_1_mapping : local_ip;
3679
                janus_network_address addr;
3680
                if(janus_network_string_to_address(janus_network_query_options_any_ip, test_ip, &addr) != 0) {
3681
                        JANUS_LOG(LOG_ERR, "Invalid address %s..?\n", test_ip);
3682
                } else {
3683
                        if(addr.family == AF_INET) {
3684
                                unsigned short int ip[4];
3685
                                sscanf(test_ip, "%hu.%hu.%hu.%hu", &ip[0], &ip[1], &ip[2], &ip[3]);
3686
                                if(ip[0] == 10) {
3687
                                        /* Class A private address */
3688
                                        private_address = TRUE;
3689
                                } else if(ip[0] == 172 && (ip[1] >= 16 && ip[1] <= 31)) {
3690
                                        /* Class B private address */
3691
                                        private_address = TRUE;
3692
                                } else if(ip[0] == 192 && ip[1] == 168) {
3693
                                        /* Class C private address */
3694
                                        private_address = TRUE;
3695
                                }
3696
                        } else {
3697
                                /* TODO Similar check for IPv6... */
3698
                        }
3699
                }
3700
                if(private_address) {
3701
                        JANUS_LOG(LOG_WARN, "Janus is deployed on a private address (%s) but you didn't specify any STUN server!"
3702
                                            " Expect trouble if this is supposed to work over the internet and not just in a LAN...\n", test_ip);
3703
                }
3704
        }
3705
        /* Are we going to force BUNDLE and/or rtcp-mux? */
3706
        gboolean force_bundle = FALSE, force_rtcpmux = FALSE;
3707
        item = janus_config_get_item_drilldown(config, "media", "force-bundle");
3708
        force_bundle = (item && item->value) ? janus_is_true(item->value) : FALSE;
3709
        janus_ice_force_bundle(force_bundle);
3710
        item = janus_config_get_item_drilldown(config, "media", "force-rtcp-mux");
3711
        force_rtcpmux = (item && item->value) ? janus_is_true(item->value) : FALSE;
3712
        janus_ice_force_rtcpmux(force_rtcpmux);
3713
        /* NACK related stuff */
3714
        item = janus_config_get_item_drilldown(config, "media", "max_nack_queue");
3715
        if(item && item->value) {
3716
                int mnq = atoi(item->value);
3717
                if(mnq < 0) {
3718
                        JANUS_LOG(LOG_WARN, "Ignoring max_nack_queue value as it's not a positive integer\n");
3719
                } else if(mnq > 0 && mnq < 200) {
3720
                        JANUS_LOG(LOG_WARN, "Ignoring max_nack_queue value as it's less than 200\n");
3721
                } else {
3722
                        janus_set_max_nack_queue(mnq);
3723
                }
3724
        }
3725
        /* no-media timer */
3726
        item = janus_config_get_item_drilldown(config, "media", "no_media_timer");
3727
        if(item && item->value) {
3728
                int nmt = atoi(item->value);
3729
                if(nmt < 0) {
3730
                        JANUS_LOG(LOG_WARN, "Ignoring no_media_timer value as it's not a positive integer\n");
3731
                } else {
3732
                        janus_set_no_media_timer(nmt);
3733
                }
3734
        }
3735

    
3736
        /* Setup OpenSSL stuff */
3737
        const char* server_pem;
3738
        item = janus_config_get_item_drilldown(config, "certificates", "cert_pem");
3739
        if(!item || !item->value) {
3740
                server_pem = NULL;
3741
        } else {
3742
                server_pem = item->value;
3743
        }
3744

    
3745
        const char* server_key;
3746
        item = janus_config_get_item_drilldown(config, "certificates", "cert_key");
3747
        if(!item || !item->value) {
3748
                server_key = NULL;
3749
        } else {
3750
                server_key = item->value;
3751
        }
3752
        JANUS_LOG(LOG_VERB, "Using certificates:\n\t%s\n\t%s\n", server_pem, server_key);
3753

    
3754
        SSL_library_init();
3755
        SSL_load_error_strings();
3756
        OpenSSL_add_all_algorithms();
3757
        /* ... and DTLS-SRTP in particular */
3758
        if(janus_dtls_srtp_init(server_pem, server_key) < 0) {
3759
                exit(1);
3760
        }
3761
        /* Check if there's any custom value for the starting MTU to use in the BIO filter */
3762
        item = janus_config_get_item_drilldown(config, "media", "dtls_mtu");
3763
        if(item && item->value)
3764
                janus_dtls_bio_filter_set_mtu(atoi(item->value));
3765

    
3766
#ifdef HAVE_SCTP
3767
        /* Initialize SCTP for DataChannels */
3768
        if(janus_sctp_init() < 0) {
3769
                exit(1);
3770
        }
3771
#else
3772
        JANUS_LOG(LOG_WARN, "Data Channels support not compiled\n");
3773
#endif
3774

    
3775
        /* Sessions */
3776
        sessions = g_hash_table_new_full(g_int64_hash, g_int64_equal, (GDestroyNotify)g_free, NULL);
3777
        old_sessions = g_hash_table_new_full(g_int64_hash, g_int64_equal, (GDestroyNotify)g_free, NULL);
3778
        janus_mutex_init(&sessions_mutex);
3779
        /* Start the sessions watchdog */
3780
        sessions_watchdog_context = g_main_context_new();
3781
        GMainLoop *watchdog_loop = g_main_loop_new(sessions_watchdog_context, FALSE);
3782
        GError *error = NULL;
3783
        GThread *watchdog = g_thread_try_new("sessions watchdog", &janus_sessions_watchdog, watchdog_loop, &error);
3784
        if(error != NULL) {
3785
                JANUS_LOG(LOG_FATAL, "Got error %d (%s) trying to start sessions watchdog...\n", error->code, error->message ? error->message : "??");
3786
                exit(1);
3787
        }
3788

    
3789
        /* Load event handlers */
3790
        const char *path = EVENTDIR;
3791
        item = janus_config_get_item_drilldown(config, "general", "events_folder");
3792
        if(item && item->value)
3793
                path = (char *)item->value;
3794
        JANUS_LOG(LOG_INFO, "Event handler plugins folder: %s\n", path);
3795
        DIR *dir = opendir(path);
3796
        if(!dir) {
3797
                /* Not really fatal, we don't care and go on anyway: event handlers are not fundamental */
3798
                JANUS_LOG(LOG_FATAL, "\tCouldn't access event handler plugins folder...\n");
3799
        } else {
3800
                /* Any event handlers to ignore? */
3801
                gchar **disabled_eventhandlers = NULL;
3802
                item = janus_config_get_item_drilldown(config, "events", "broadcast");
3803
                /* Event handlers are disabled by default: they need to be enabled in the configuration */
3804
                gboolean enable_events = FALSE;
3805
                if(item && item->value)
3806
                        enable_events = janus_is_true(item->value);
3807
                if(!enable_events) {
3808
                        JANUS_LOG(LOG_WARN, "Event handlers support disabled\n");
3809
                } else {
3810
                        item = janus_config_get_item_drilldown(config, "events", "disable");
3811
                        if(item && item->value)
3812
                                disabled_eventhandlers = g_strsplit(item->value, ",", -1);
3813
                        /* Open the shared objects */
3814
                        struct dirent *eventent = NULL;
3815
                        char eventpath[1024];
3816
                        while((eventent = readdir(dir))) {
3817
                                int len = strlen(eventent->d_name);
3818
                                if (len < 4) {
3819
                                        continue;
3820
                                }
3821
                                if (strcasecmp(eventent->d_name+len-strlen(SHLIB_EXT), SHLIB_EXT)) {
3822
                                        continue;
3823
                                }
3824
                                /* Check if this event handler has been disabled in the configuration file */
3825
                                if(disabled_eventhandlers != NULL) {
3826
                                        gchar *index = disabled_eventhandlers[0];
3827
                                        if(index != NULL) {
3828
                                                int i=0;
3829
                                                gboolean skip = FALSE;
3830
                                                while(index != NULL) {
3831
                                                        while(isspace(*index))
3832
                                                                index++;
3833
                                                        if(strlen(index) && !strcmp(index, eventent->d_name)) {
3834
                                                                JANUS_LOG(LOG_WARN, "Event handler plugin '%s' has been disabled, skipping...\n", eventent->d_name);
3835
                                                                skip = TRUE;
3836
                                                                break;
3837
                                                        }
3838
                                                        i++;
3839
                                                        index = disabled_eventhandlers[i];
3840
                                                }
3841
                                                if(skip)
3842
                                                        continue;
3843
                                        }
3844
                                }
3845
                                JANUS_LOG(LOG_INFO, "Loading event handler plugin '%s'...\n", eventent->d_name);
3846
                                memset(eventpath, 0, 1024);
3847
                                g_snprintf(eventpath, 1024, "%s/%s", path, eventent->d_name);
3848
                                void *event = dlopen(eventpath, RTLD_LAZY);
3849
                                if (!event) {
3850
                                        JANUS_LOG(LOG_ERR, "\tCouldn't load event handler plugin '%s': %s\n", eventent->d_name, dlerror());
3851
                                } else {
3852
                                        create_e *create = (create_e*) dlsym(event, "create");
3853
                                        const char *dlsym_error = dlerror();
3854
                                        if (dlsym_error) {
3855
                                                JANUS_LOG(LOG_ERR, "\tCouldn't load symbol 'create': %s\n", dlsym_error);
3856
                                                continue;
3857
                                        }
3858
                                        janus_eventhandler *janus_eventhandler = create();
3859
                                        if(!janus_eventhandler) {
3860
                                                JANUS_LOG(LOG_ERR, "\tCouldn't use function 'create'...\n");
3861
                                                continue;
3862
                                        }
3863
                                        /* Are all the mandatory methods and callbacks implemented? */
3864
                                        if(!janus_eventhandler->init || !janus_eventhandler->destroy ||
3865
                                                        !janus_eventhandler->get_api_compatibility ||
3866
                                                        !janus_eventhandler->get_version ||
3867
                                                        !janus_eventhandler->get_version_string ||
3868
                                                        !janus_eventhandler->get_description ||
3869
                                                        !janus_eventhandler->get_package ||
3870
                                                        !janus_eventhandler->get_name ||
3871
                                                        !janus_eventhandler->incoming_event) {
3872
                                                JANUS_LOG(LOG_ERR, "\tMissing some mandatory methods/callbacks, skipping this event handler plugin...\n");
3873
                                                continue;
3874
                                        }
3875
                                        if(janus_eventhandler->get_api_compatibility() < JANUS_EVENTHANDLER_API_VERSION) {
3876
                                                JANUS_LOG(LOG_ERR, "The '%s' event handler plugin was compiled against an older version of the API (%d < %d), skipping it: update it to enable it again\n",
3877
                                                        janus_eventhandler->get_package(), janus_eventhandler->get_api_compatibility(), JANUS_EVENTHANDLER_API_VERSION);
3878
                                                continue;
3879
                                        }
3880
                                        janus_eventhandler->init(configs_folder);
3881
                                        JANUS_LOG(LOG_VERB, "\tVersion: %d (%s)\n", janus_eventhandler->get_version(), janus_eventhandler->get_version_string());
3882
                                        JANUS_LOG(LOG_VERB, "\t   [%s] %s\n", janus_eventhandler->get_package(), janus_eventhandler->get_name());
3883
                                        JANUS_LOG(LOG_VERB, "\t   %s\n", janus_eventhandler->get_description());
3884
                                        JANUS_LOG(LOG_VERB, "\t   Plugin API version: %d\n", janus_eventhandler->get_api_compatibility());
3885
                                        JANUS_LOG(LOG_VERB, "\t   Subscriptions:");
3886
                                        if(janus_eventhandler->events_mask == 0) {
3887
                                                JANUS_LOG(LOG_VERB, " none");
3888
                                        } else {
3889
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_SESSION))
3890
                                                        JANUS_LOG(LOG_VERB, " sessions");
3891
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_HANDLE))
3892
                                                        JANUS_LOG(LOG_VERB, " handles");
3893
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_JSEP))
3894
                                                        JANUS_LOG(LOG_VERB, " jsep");
3895
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_WEBRTC))
3896
                                                        JANUS_LOG(LOG_VERB, " webrtc");
3897
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_MEDIA))
3898
                                                        JANUS_LOG(LOG_VERB, " media");
3899
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_PLUGIN))
3900
                                                        JANUS_LOG(LOG_VERB, " plugins");
3901
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_TRANSPORT))
3902
                                                        JANUS_LOG(LOG_VERB, " transports");
3903
                                        }
3904
                                        JANUS_LOG(LOG_VERB, "\n");
3905
                                        if(eventhandlers == NULL)
3906
                                                eventhandlers = g_hash_table_new(g_str_hash, g_str_equal);
3907
                                        g_hash_table_insert(eventhandlers, (gpointer)janus_eventhandler->get_package(), janus_eventhandler);
3908
                                        if(eventhandlers_so == NULL)
3909
                                                eventhandlers_so = g_hash_table_new(g_str_hash, g_str_equal);
3910
                                        g_hash_table_insert(eventhandlers_so, (gpointer)janus_eventhandler->get_package(), event);
3911
                                }
3912
                        }
3913
                }
3914
                closedir(dir);
3915
                if(disabled_eventhandlers != NULL)
3916
                        g_strfreev(disabled_eventhandlers);
3917
                disabled_eventhandlers = NULL;
3918
                /* Initialize the event broadcaster */
3919
                if(janus_events_init(enable_events, eventhandlers) < 0) {
3920
                        JANUS_LOG(LOG_FATAL, "Error initializing the Event handlers mechanism...\n");
3921
                        exit(1);
3922
                }
3923
        }
3924

    
3925
        /* Load plugins */
3926
        path = PLUGINDIR;
3927
        item = janus_config_get_item_drilldown(config, "general", "plugins_folder");
3928
        if(item && item->value)
3929
                path = (char *)item->value;
3930
        JANUS_LOG(LOG_INFO, "Plugins folder: %s\n", path);
3931
        dir = opendir(path);
3932
        if(!dir) {
3933
                JANUS_LOG(LOG_FATAL, "\tCouldn't access plugins folder...\n");
3934
                exit(1);
3935
        }
3936
        /* Any plugin to ignore? */
3937
        gchar **disabled_plugins = NULL;
3938
        item = janus_config_get_item_drilldown(config, "plugins", "disable");
3939
        if(item && item->value)
3940
                disabled_plugins = g_strsplit(item->value, ",", -1);
3941
        /* Open the shared objects */
3942
        struct dirent *pluginent = NULL;
3943
        char pluginpath[1024];
3944
        while((pluginent = readdir(dir))) {
3945
                int len = strlen(pluginent->d_name);
3946