Statistics
| Branch: | Revision:

janus-gateway / janus.c @ e67b71f9

History | View | Annotate | Download (180 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 "cmdline.h"
30
#include "config.h"
31
#include "apierror.h"
32
#include "log.h"
33
#include "debug.h"
34
#include "rtcp.h"
35
#include "auth.h"
36
#include "events.h"
37

    
38

    
39
#define JANUS_NAME                                "Janus WebRTC Gateway"
40
#define JANUS_AUTHOR                        "Meetecho s.r.l."
41
#define JANUS_VERSION                        22
42
#define JANUS_VERSION_STRING        "0.2.2"
43
#define JANUS_SERVER_NAME                "MyJanusInstance"
44

    
45
#ifdef __MACH__
46
#define SHLIB_EXT "0.dylib"
47
#else
48
#define SHLIB_EXT ".so"
49
#endif
50

    
51

    
52
static janus_config *config = NULL;
53
static char *config_file = NULL;
54
static char *configs_folder = NULL;
55

    
56
static GHashTable *transports = NULL;
57
static GHashTable *transports_so = NULL;
58

    
59
static GHashTable *eventhandlers = NULL;
60
static GHashTable *eventhandlers_so = NULL;
61

    
62
static GHashTable *plugins = NULL;
63
static GHashTable *plugins_so = NULL;
64

    
65

    
66
/* Daemonization */
67
static gboolean daemonize = FALSE;
68
static int pipefd[2];
69

    
70

    
71
/* API secrets */
72
static char *api_secret = NULL, *admin_api_secret = NULL;
73

    
74
/* JSON parameters */
75
static int janus_process_error_string(janus_request *request, uint64_t session_id, const char *transaction, gint error, gchar *error_string);
76

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

    
128
/* Admin/Monitor helpers */
129
json_t *janus_admin_stream_summary(janus_ice_stream *stream);
130
json_t *janus_admin_component_summary(janus_ice_component *component);
131

    
132

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

    
155

    
156
/* Public instance name */
157
static gchar *server_name = NULL;
158

    
159

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

    
175

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

    
281
        return info;
282
}
283

    
284

    
285
/* Logging */
286
int janus_log_level = LOG_INFO;
287
gboolean janus_log_timestamps = FALSE;
288
gboolean janus_log_colors = FALSE;
289
int lock_debug = 0;
290

    
291

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

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

    
329

    
330
/** @name Transport plugin callback interface
331
 * These are the callbacks implemented by the gateway core, as part of
332
 * the janus_transport_callbacks interface. Everything the transport
333
 * plugins send the gateway is handled here.
334
 */
335
///@{
336
void janus_transport_incoming_request(janus_transport *plugin, void *transport, void *request_id, gboolean admin, json_t *message, json_error_t *error);
337
void janus_transport_gone(janus_transport *plugin, void *transport);
338
gboolean janus_transport_is_api_secret_needed(janus_transport *plugin);
339
gboolean janus_transport_is_api_secret_valid(janus_transport *plugin, const char *apisecret);
340
gboolean janus_transport_is_auth_token_needed(janus_transport *plugin);
341
gboolean janus_transport_is_auth_token_valid(janus_transport *plugin, const char *token);
342
void janus_transport_notify_event(janus_transport *plugin, void *transport, json_t *event);
343

    
344
static janus_transport_callbacks janus_handler_transport =
345
        {
346
                .incoming_request = janus_transport_incoming_request,
347
                .transport_gone = janus_transport_gone,
348
                .is_api_secret_needed = janus_transport_is_api_secret_needed,
349
                .is_api_secret_valid = janus_transport_is_api_secret_valid,
350
                .is_auth_token_needed = janus_transport_is_auth_token_needed,
351
                .is_auth_token_valid = janus_transport_is_auth_token_valid,
352
                .events_is_enabled = janus_events_is_enabled,
353
                .notify_event = janus_transport_notify_event,
354
        };
355
GThreadPool *tasks = NULL;
356
void janus_transport_task(gpointer data, gpointer user_data);
357
///@}
358

    
359

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

    
387

    
388
/* Gateway Sessions */
389
static janus_mutex sessions_mutex;
390
static GHashTable *sessions = NULL, *old_sessions = NULL;
391
static GMainContext *sessions_watchdog_context = NULL;
392

    
393

    
394
static gboolean janus_cleanup_session(gpointer user_data) {
395
        janus_session *session = (janus_session *) user_data;
396

    
397
        JANUS_LOG(LOG_DBG, "Cleaning up session %"SCNu64"...\n", session->session_id);
398
        janus_session_destroy(session->session_id);
399

    
400
        return G_SOURCE_REMOVE;
401
}
402

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

    
421
                                /* Notify the transport */
422
                                if(session->source) {
423
                                        json_t *event = json_object();
424
                                        json_object_set_new(event, "janus", json_string("timeout"));
425
                                        json_object_set_new(event, "session_id", json_integer(session->session_id));
426
                                        /* Send this to the transport client */
427
                                        session->source->transport->send_message(session->source->instance, NULL, FALSE, event);
428
                                        /* Notify the transport plugin about the session timeout */
429
                                        session->source->transport->session_over(session->source->instance, session->session_id, TRUE);
430
                                }
431
                                /* Notify event handlers as well */
432
                                if(janus_events_is_enabled())
433
                                        janus_events_notify_handlers(JANUS_EVENT_TYPE_SESSION, session->session_id, "timeout", NULL);
434

    
435
                                /* Mark the session as over, we'll deal with it later */
436
                                session->timeout = 1;
437
                                /* FIXME Is this safe? apparently it causes hash table errors on the console */
438
                                g_hash_table_iter_remove(&iter);
439
                                g_hash_table_insert(old_sessions, janus_uint64_dup(session->session_id), session);
440

    
441
                                /* Schedule the session for deletion */
442
                                GSource *timeout_source = g_timeout_source_new_seconds(3);
443
                                g_source_set_callback(timeout_source, janus_cleanup_session, session, NULL);
444
                                g_source_attach(timeout_source, watchdog_context);
445
                                g_source_unref(timeout_source);
446
                        }
447
                }
448
        }
449
        janus_mutex_unlock(&sessions_mutex);
450

    
451
        return G_SOURCE_CONTINUE;
452
}
453

    
454
static gpointer janus_sessions_watchdog(gpointer user_data) {
455
        GMainLoop *loop = (GMainLoop *) user_data;
456
        GMainContext *watchdog_context = g_main_loop_get_context(loop);
457
        GSource *timeout_source;
458

    
459
        timeout_source = g_timeout_source_new_seconds(2);
460
        g_source_set_callback(timeout_source, janus_check_sessions, watchdog_context, NULL);
461
        g_source_attach(timeout_source, watchdog_context);
462
        g_source_unref(timeout_source);
463

    
464
        JANUS_LOG(LOG_INFO, "Sessions watchdog started\n");
465

    
466
        g_main_loop_run(loop);
467

    
468
        return NULL;
469
}
470

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

    
499
janus_session *janus_session_find(guint64 session_id) {
500
        janus_mutex_lock(&sessions_mutex);
501
        janus_session *session = g_hash_table_lookup(sessions, &session_id);
502
        janus_mutex_unlock(&sessions_mutex);
503
        return session;
504
}
505

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

    
513
void janus_session_notify_event(guint64 session_id, json_t *event) {
514
        janus_mutex_lock(&sessions_mutex);
515
        janus_session *session = sessions ? g_hash_table_lookup(sessions, &session_id) : NULL;
516
        if(session != NULL && !session->destroy && session->source != NULL && session->source->transport != NULL) {
517
                janus_mutex_unlock(&sessions_mutex);
518
                /* Send this to the transport client */
519
                JANUS_LOG(LOG_HUGE, "Sending event to %s (%p)\n", session->source->transport->get_package(), session->source->instance);
520
                session->source->transport->send_message(session->source->instance, NULL, FALSE, event);
521
        } else {
522
                janus_mutex_unlock(&sessions_mutex);
523
                /* No transport, free the event */
524
                json_decref(event);
525
        }
526
}
527

    
528

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

    
553
        /* FIXME Actually destroy session */
554
        janus_session_free(session);
555

    
556
        return 0;
557
}
558

    
559
void janus_session_free(janus_session *session) {
560
        if(session == NULL)
561
                return;
562
        janus_mutex_lock(&session->mutex);
563
        if(session->ice_handles != NULL) {
564
                g_hash_table_destroy(session->ice_handles);
565
                session->ice_handles = NULL;
566
        }
567
        if(session->source != NULL) {
568
                janus_request_destroy(session->source);
569
                session->source = NULL;
570
        }
571
        janus_mutex_unlock(&session->mutex);
572
        g_free(session);
573
        session = NULL;
574
}
575

    
576

    
577
/* Requests management */
578
janus_request *janus_request_new(janus_transport *transport, void *instance, void *request_id, gboolean admin, json_t *message) {
579
        janus_request *request = (janus_request *)g_malloc0(sizeof(janus_request));
580
        request->transport = transport;
581
        request->instance = instance;
582
        request->request_id = request_id;
583
        request->admin = admin;
584
        request->message = message;
585
        return request;
586
}
587

    
588
void janus_request_destroy(janus_request *request) {
589
        if(request == NULL)
590
                return;
591
        request->transport = NULL;
592
        request->instance = NULL;
593
        request->request_id = NULL;
594
        if(request->message)
595
                json_decref(request->message);
596
        request->message = NULL;
597
        g_free(request);
598
}
599

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

    
618
        /* Get transaction and message request */
619
        JANUS_VALIDATE_JSON_OBJECT(root, incoming_request_parameters,
620
                error_code, error_cause, FALSE,
621
                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
622
        if(error_code != 0) {
623
                ret = janus_process_error_string(request, session_id, NULL, error_code, error_cause);
624
                goto jsondone;
625
        }
626
        json_t *transaction = json_object_get(root, "transaction");
627
        const gchar *transaction_text = json_string_value(transaction);
628
        json_t *message = json_object_get(root, "janus");
629
        const gchar *message_text = json_string_value(message);
630

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

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

    
759
        /* If we got here, make sure we have a session (and/or a handle) */
760
        janus_session *session = janus_session_find(session_id);
761
        if(!session) {
762
                JANUS_LOG(LOG_ERR, "Couldn't find any session %"SCNu64"...\n", session_id);
763
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, "No such session %"SCNu64"", session_id);
764
                goto jsondone;
765
        }
766
        /* Update the last activity timer */
767
        session->last_activity = janus_get_monotonic_time();
768
        janus_ice_handle *handle = NULL;
769
        if(handle_id > 0) {
770
                handle = janus_ice_handle_find(session, handle_id);
771
                if(!handle) {
772
                        JANUS_LOG(LOG_ERR, "Couldn't find any handle %"SCNu64" in session %"SCNu64"...\n", handle_id, session_id);
773
                        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);
774
                        goto jsondone;
775
                }
776
        }
777

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

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

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

    
1323
                /* Make sure the app handle is still valid */
1324
                if(handle->app == NULL || handle->app_handle == NULL || !janus_plugin_session_is_alive(handle->app_handle)) {
1325
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE, "No plugin to handle this message");
1326
                        g_free(jsep_type);
1327
                        g_free(jsep_sdp_stripped);
1328
                        janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
1329
                        goto jsondone;
1330
                }
1331

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

    
1469
trickledone:
1470
                janus_mutex_unlock(&handle->mutex);
1471
                /* We reply right away, not to block the web server... */
1472
                json_t *reply = json_object();
1473
                json_object_set_new(reply, "janus", json_string("ack"));
1474
                json_object_set_new(reply, "session_id", json_integer(session_id));
1475
                json_object_set_new(reply, "transaction", json_string(transaction_text));
1476
                /* Send the success reply */
1477
                ret = janus_process_success(request, reply);
1478
        } else {
1479
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN_REQUEST, "Unknown request '%s'", message_text);
1480
        }
1481

    
1482
jsondone:
1483
        /* Done processing */
1484
        return ret;
1485
}
1486

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

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

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

    
2074
        /* Go on with the processing */
2075
        if(admin_api_secret != NULL) {
2076
                /* There's an API secret, check that the client provided it */
2077
                json_t *secret = json_object_get(root, "admin_secret");
2078
                if(!secret || !json_is_string(secret) || !janus_strcmp_const_time(json_string_value(secret), admin_api_secret)) {
2079
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNAUTHORIZED, NULL);
2080
                        goto jsondone;
2081
                }
2082
        }
2083

    
2084
        /* If we got here, make sure we have a session (and/or a handle) */
2085
        janus_session *session = janus_session_find(session_id);
2086
        if(!session) {
2087
                JANUS_LOG(LOG_ERR, "Couldn't find any session %"SCNu64"...\n", session_id);
2088
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, "No such session %"SCNu64"", session_id);
2089
                goto jsondone;
2090
        }
2091
        janus_ice_handle *handle = NULL;
2092
        if(handle_id > 0) {
2093
                handle = janus_ice_handle_find(session, handle_id);
2094
                if(!handle) {
2095
                        JANUS_LOG(LOG_ERR, "Couldn't find any handle %"SCNu64" in session %"SCNu64"...\n", handle_id, session_id);
2096
                        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);
2097
                        goto jsondone;
2098
                }
2099
        }
2100

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

    
2236
jsondone:
2237
        /* Done processing */
2238
        return ret;
2239
}
2240

    
2241
int janus_process_success(janus_request *request, json_t *payload)
2242
{
2243
        if(!request || !payload)
2244
                return -1;
2245
        /* Pass to the right transport plugin */
2246
        JANUS_LOG(LOG_HUGE, "Sending %s API response to %s (%p)\n", request->admin ? "admin" : "Janus", request->transport->get_package(), request->instance);
2247
        return request->transport->send_message(request->instance, request->request_id, request->admin, payload);
2248
}
2249

    
2250
static int janus_process_error_string(janus_request *request, uint64_t session_id, const char *transaction, gint error, gchar *error_string)
2251
{
2252
        if(!request)
2253
                return -1;
2254
        /* Done preparing error */
2255
        JANUS_LOG(LOG_VERB, "[%s] Returning %s API error %d (%s)\n", transaction, request->admin ? "admin" : "Janus", error, error_string);
2256
        /* Prepare JSON error */
2257
        json_t *reply = json_object();
2258
        json_object_set_new(reply, "janus", json_string("error"));
2259
        if(session_id > 0)
2260
                json_object_set_new(reply, "session_id", json_integer(session_id));
2261
        if(transaction != NULL)
2262
                json_object_set_new(reply, "transaction", json_string(transaction));
2263
        json_t *error_data = json_object();
2264
        json_object_set_new(error_data, "code", json_integer(error));
2265
        json_object_set_new(error_data, "reason", json_string(error_string));
2266
        json_object_set_new(reply, "error", error_data);
2267
        /* Pass to the right transport plugin */
2268
        return request->transport->send_message(request->instance, request->request_id, request->admin, reply);
2269
}
2270

    
2271
int janus_process_error(janus_request *request, uint64_t session_id, const char *transaction, gint error, const char *format, ...)
2272
{
2273
        if(!request)
2274
                return -1;
2275
        gchar *error_string = NULL;
2276
        gchar error_buf[512];
2277
        if(format == NULL) {
2278
                /* No error string provided, use the default one */
2279
                error_string = (gchar *)janus_get_api_error(error);
2280
        } else {
2281
                /* This callback has variable arguments (error string) */
2282
                va_list ap;
2283
                va_start(ap, format);
2284
                g_vsnprintf(error_buf, sizeof(error_buf), format, ap);
2285
                va_end(ap);
2286
                error_string = error_buf;
2287
        }
2288
        return janus_process_error_string(request, session_id, transaction, error, error_string);
2289
}
2290

    
2291
/* Admin/monitor helpers */
2292
json_t *janus_admin_stream_summary(janus_ice_stream *stream) {
2293
        if(stream == NULL)
2294
                return NULL;
2295
        json_t *s = json_object();
2296
        json_object_set_new(s, "id", json_integer(stream->stream_id));
2297
        json_object_set_new(s, "ready", json_integer(stream->cdone));
2298
        json_object_set_new(s, "disabled", stream->disabled ? json_true() : json_false());
2299
        json_t *ss = json_object();
2300
        if(stream->audio_ssrc)
2301
                json_object_set_new(ss, "audio", json_integer(stream->audio_ssrc));
2302
        if(stream->video_ssrc)
2303
                json_object_set_new(ss, "video", json_integer(stream->video_ssrc));
2304
        if(stream->audio_ssrc_peer)
2305
                json_object_set_new(ss, "audio-peer", json_integer(stream->audio_ssrc_peer));
2306
        if(stream->video_ssrc_peer)
2307
                json_object_set_new(ss, "video-peer", json_integer(stream->video_ssrc_peer));
2308
        if(stream->video_ssrc_peer_rtx)
2309
                json_object_set_new(ss, "video-peer-rtx", json_integer(stream->video_ssrc_peer_rtx));
2310
        json_object_set_new(s, "ssrc", ss);
2311
        json_t *components = json_array();
2312
        if(stream->rtp_component) {
2313
                json_t *c = janus_admin_component_summary(stream->rtp_component);
2314
                if(c)
2315
                        json_array_append_new(components, c);
2316
        }
2317
        if(stream->rtcp_component) {
2318
                json_t *c = janus_admin_component_summary(stream->rtcp_component);
2319
                if(c)
2320
                        json_array_append_new(components, c);
2321
        }
2322
        json_t *rtcp_stats = NULL;
2323
        if(stream->audio_rtcp_ctx != NULL) {
2324
                rtcp_stats = json_object();
2325
                json_t *audio_rtcp_stats = json_object();
2326
                json_object_set_new(audio_rtcp_stats, "base", json_integer(stream->audio_rtcp_ctx->tb));
2327
                json_object_set_new(audio_rtcp_stats, "lsr", json_integer(janus_rtcp_context_get_lsr(stream->audio_rtcp_ctx)));
2328
                json_object_set_new(audio_rtcp_stats, "lost", json_integer(janus_rtcp_context_get_lost_all(stream->audio_rtcp_ctx, FALSE)));
2329
                json_object_set_new(audio_rtcp_stats, "lost-by-remote", json_integer(janus_rtcp_context_get_lost_all(stream->audio_rtcp_ctx, TRUE)));
2330
                json_object_set_new(audio_rtcp_stats, "jitter-local", json_integer(janus_rtcp_context_get_jitter(stream->audio_rtcp_ctx, FALSE)));
2331
                json_object_set_new(audio_rtcp_stats, "jitter-remote", json_integer(janus_rtcp_context_get_jitter(stream->audio_rtcp_ctx, TRUE)));
2332
                json_object_set_new(rtcp_stats, "audio", audio_rtcp_stats);
2333
        }
2334
        if(stream->video_rtcp_ctx != NULL) {
2335
                if(rtcp_stats == NULL)
2336
                        rtcp_stats = json_object();
2337
                json_t *video_rtcp_stats = json_object();
2338
                json_object_set_new(video_rtcp_stats, "base", json_integer(stream->video_rtcp_ctx->tb));
2339
                json_object_set_new(video_rtcp_stats, "lsr", json_integer(janus_rtcp_context_get_lsr(stream->video_rtcp_ctx)));
2340
                json_object_set_new(video_rtcp_stats, "lost", json_integer(janus_rtcp_context_get_lost_all(stream->video_rtcp_ctx, FALSE)));
2341
                json_object_set_new(video_rtcp_stats, "lost-by-remote", json_integer(janus_rtcp_context_get_lost_all(stream->video_rtcp_ctx, TRUE)));
2342
                json_object_set_new(video_rtcp_stats, "jitter-local", json_integer(janus_rtcp_context_get_jitter(stream->video_rtcp_ctx, FALSE)));
2343
                json_object_set_new(video_rtcp_stats, "jitter-remote", json_integer(janus_rtcp_context_get_jitter(stream->video_rtcp_ctx, TRUE)));
2344
                json_object_set_new(rtcp_stats, "video", video_rtcp_stats);
2345
        }
2346
        if(rtcp_stats != NULL)
2347
                json_object_set_new(s, "rtcp_stats", rtcp_stats);
2348
        json_object_set_new(s, "components", components);
2349
        return s;
2350
}
2351

    
2352
json_t *janus_admin_component_summary(janus_ice_component *component) {
2353
        if(component == NULL)
2354
                return NULL;
2355
        janus_ice_handle *handle = component->stream ? component->stream->handle : NULL;
2356
        json_t *c = json_object();
2357
        json_object_set_new(c, "id", json_integer(component->component_id));
2358
        json_object_set_new(c, "state", json_string(janus_get_ice_state_name(component->state)));
2359
        if(component->component_connected > 0)
2360
                json_object_set_new(c, "connected", json_integer(component->component_connected));
2361
        if(component->local_candidates) {
2362
                json_t *cs = json_array();
2363
                GSList *candidates = component->local_candidates, *i = NULL;
2364
                for (i = candidates; i; i = i->next) {
2365
                        gchar *lc = (gchar *) i->data;
2366
                        if(lc)
2367
                                json_array_append_new(cs, json_string(lc));
2368
                }
2369
                json_object_set_new(c, "local-candidates", cs);
2370
        }
2371
        if(component->remote_candidates) {
2372
                json_t *cs = json_array();
2373
                GSList *candidates = component->remote_candidates, *i = NULL;
2374
                for (i = candidates; i; i = i->next) {
2375
                        gchar *rc = (gchar *) i->data;
2376
                        if(rc)
2377
                                json_array_append_new(cs, json_string(rc));
2378
                }
2379
                json_object_set_new(c, "remote-candidates", cs);
2380
        }
2381
        if(component->selected_pair) {
2382
                json_object_set_new(c, "selected-pair", json_string(component->selected_pair));
2383
        }
2384
        json_t *d = json_object();
2385
        json_t *in_stats = json_object();
2386
        json_t *out_stats = json_object();
2387
        if(component->dtls) {
2388
                janus_dtls_srtp *dtls = component->dtls;
2389
                json_object_set_new(d, "fingerprint", json_string(janus_dtls_get_local_fingerprint()));
2390
                json_object_set_new(d, "remote-fingerprint", json_string(component->stream->remote_fingerprint));
2391
                json_object_set_new(d, "remote-fingerprint-hash", json_string(component->stream->remote_hashing));
2392
                json_object_set_new(d, "dtls-role", json_string(janus_get_dtls_srtp_role(component->stream->dtls_role)));
2393
                json_object_set_new(d, "dtls-state", json_string(janus_get_dtls_srtp_state(dtls->dtls_state)));
2394
                json_object_set_new(d, "valid", dtls->srtp_valid ? json_true() : json_false());
2395
                json_object_set_new(d, "ready", dtls->ready ? json_true() : json_false());
2396
                if(dtls->dtls_connected > 0)
2397
                        json_object_set_new(d, "connected", json_integer(dtls->dtls_connected));
2398
                if(handle && janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_AUDIO)) {
2399
                        json_object_set_new(in_stats, "audio_packets", json_integer(component->in_stats.audio_packets));
2400
                        json_object_set_new(in_stats, "audio_bytes", json_integer(component->in_stats.audio_bytes));
2401
                        json_object_set_new(in_stats, "audio_nacks", json_integer(component->in_stats.audio_nacks));
2402
                        /* Compute the last second stuff too */
2403
                        gint64 now = janus_get_monotonic_time();
2404
                        guint64 bytes = 0;
2405
                        if(component->in_stats.audio_bytes_lastsec) {
2406
                                GList *lastsec = component->in_stats.audio_bytes_lastsec;
2407
                                while(lastsec) {
2408
                                        janus_ice_stats_item *s = (janus_ice_stats_item *)lastsec->data;
2409
                                        if(s && now-s->when < G_USEC_PER_SEC)
2410
                                                bytes += s->bytes;
2411
                                        lastsec = lastsec->next;
2412
                                }
2413
                        }
2414
                        json_object_set_new(in_stats, "audio_bytes_lastsec", json_integer(bytes));
2415
                }
2416
                if(handle && janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_VIDEO)) {
2417
                        json_object_set_new(in_stats, "video_packets", json_integer(component->in_stats.video_packets));
2418
                        json_object_set_new(in_stats, "video_bytes", json_integer(component->in_stats.video_bytes));
2419
                        json_object_set_new(in_stats, "video_nacks", json_integer(component->in_stats.video_nacks));
2420
                        /* Compute the last second stuff too */
2421
                        gint64 now = janus_get_monotonic_time();
2422
                        guint64 bytes = 0;
2423
                        if(component->in_stats.video_bytes_lastsec) {
2424
                                GList *lastsec = component->in_stats.video_bytes_lastsec;
2425
                                while(lastsec) {
2426
                                        janus_ice_stats_item *s = (janus_ice_stats_item *)lastsec->data;
2427
                                        if(s && now-s->when < G_USEC_PER_SEC)
2428
                                                bytes += s->bytes;
2429
                                        lastsec = lastsec->next;
2430
                                }
2431
                        }
2432
                        json_object_set_new(in_stats, "video_bytes_lastsec", json_integer(bytes));
2433
                }
2434
                json_object_set_new(in_stats, "data_packets", json_integer(component->in_stats.data_packets));
2435
                json_object_set_new(in_stats, "data_bytes", json_integer(component->in_stats.data_bytes));
2436
                if(handle && janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_AUDIO)) {
2437
                        json_object_set_new(out_stats, "audio_packets", json_integer(component->out_stats.audio_packets));
2438
                        json_object_set_new(out_stats, "audio_bytes", json_integer(component->out_stats.audio_bytes));
2439
                        json_object_set_new(out_stats, "audio_nacks", json_integer(component->out_stats.audio_nacks));
2440
                }
2441
                if(handle && janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_VIDEO)) {
2442
                        json_object_set_new(out_stats, "video_packets", json_integer(component->out_stats.video_packets));
2443
                        json_object_set_new(out_stats, "video_bytes", json_integer(component->out_stats.video_bytes));
2444
                        json_object_set_new(out_stats, "video_nacks", json_integer(component->out_stats.video_nacks));
2445
                }
2446
                json_object_set_new(out_stats, "data_packets", json_integer(component->out_stats.data_packets));
2447
                json_object_set_new(out_stats, "data_bytes", json_integer(component->out_stats.data_bytes));
2448
#ifdef HAVE_SCTP
2449
                /* FIXME Actually check if this succeeded? */
2450
                json_object_set_new(d, "sctp-association", dtls->sctp ? json_true() : json_false());
2451
#endif
2452
        }
2453
        json_object_set_new(c, "dtls", d);
2454
        json_object_set_new(c, "in_stats", in_stats);
2455
        json_object_set_new(c, "out_stats", out_stats);
2456
        return c;
2457
}
2458

    
2459

    
2460
/* Transports */
2461
void janus_transport_close(gpointer key, gpointer value, gpointer user_data) {
2462
        janus_transport *transport = (janus_transport *)value;
2463
        if(!transport)
2464
                return;
2465
        transport->destroy();
2466
}
2467

    
2468
void janus_transportso_close(gpointer key, gpointer value, gpointer user_data) {
2469
        void *transport = value;
2470
        if(!transport)
2471
                return;
2472
        /* FIXME We don't dlclose transports to be sure we can detect leaks */
2473
        //~ dlclose(transport);
2474
}
2475

    
2476
/* Transport callback interface */
2477
void janus_transport_incoming_request(janus_transport *plugin, void *transport, void *request_id, gboolean admin, json_t *message, json_error_t *error) {
2478
        JANUS_LOG(LOG_VERB, "Got %s API request from %s (%p)\n", admin ? "an admin" : "a Janus", plugin->get_package(), transport);
2479
        /* Create a janus_request instance to handle the request */
2480
        janus_request *request = janus_request_new(plugin, transport, request_id, admin, message);
2481
        GError *tperror = NULL;
2482
        g_thread_pool_push(tasks, request, &tperror);
2483
        if(tperror != NULL) {
2484
                /* Something went wrong... */
2485
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to push task in thread pool...\n", tperror->code, tperror->message ? tperror->message : "??");
2486
                json_t *transaction = json_object_get(message, "transaction");
2487
                const char *transaction_text = json_is_string(transaction) ? json_string_value(transaction) : NULL;
2488
                janus_process_error(request, 0, transaction_text, JANUS_ERROR_UNKNOWN, "Thread pool error");
2489
                janus_request_destroy(request);
2490
        }
2491
}
2492

    
2493
void janus_transport_gone(janus_transport *plugin, void *transport) {
2494
        /* Get rid of sessions this transport was handling */
2495
        JANUS_LOG(LOG_VERB, "A %s transport instance has gone away (%p)\n", plugin->get_package(), transport);
2496
        janus_mutex_lock(&sessions_mutex);
2497
        if(sessions && g_hash_table_size(sessions) > 0) {
2498
                GHashTableIter iter;
2499
                gpointer value;
2500
                g_hash_table_iter_init(&iter, sessions);
2501
                while(g_hash_table_iter_next(&iter, NULL, &value)) {
2502
                        janus_session *session = (janus_session *) value;
2503
                        if(!session || session->destroy || session->timeout || session->last_activity == 0)
2504
                                continue;
2505
                        if(session->source && session->source->instance == transport) {
2506
                                JANUS_LOG(LOG_VERB, "  -- Marking Session %"SCNu64" as over\n", session->session_id);
2507
                                session->last_activity = 0;        /* This will trigger a timeout */
2508
                        }
2509
                }
2510
        }
2511
        janus_mutex_unlock(&sessions_mutex);
2512
}
2513

    
2514
gboolean janus_transport_is_api_secret_needed(janus_transport *plugin) {
2515
        return api_secret != NULL;
2516
}
2517

    
2518
gboolean janus_transport_is_api_secret_valid(janus_transport *plugin, const char *apisecret) {
2519
        if(api_secret == NULL)
2520
                return TRUE;
2521
        return apisecret && janus_strcmp_const_time(apisecret, api_secret);
2522
}
2523

    
2524
gboolean janus_transport_is_auth_token_needed(janus_transport *plugin) {
2525
        return janus_auth_is_enabled();
2526
}
2527

    
2528
gboolean janus_transport_is_auth_token_valid(janus_transport *plugin, const char *token) {
2529
        if(!janus_auth_is_enabled())
2530
                return TRUE;
2531
        return token && janus_auth_check_token(token);
2532
}
2533

    
2534
void janus_transport_notify_event(janus_transport *plugin, void *transport, json_t *event) {
2535
        /* A plugin asked to notify an event to the handlers */
2536
        if(!plugin || !event || !json_is_object(event))
2537
                return;
2538
        /* Notify event handlers */
2539
        if(janus_events_is_enabled()) {
2540
                janus_events_notify_handlers(JANUS_EVENT_TYPE_TRANSPORT,
2541
                        0, plugin->get_package(), transport, event);
2542
        } else {
2543
                json_decref(event);
2544
        }
2545
}
2546

    
2547
void janus_transport_task(gpointer data, gpointer user_data) {
2548
        JANUS_LOG(LOG_VERB, "Transport task pool, serving request\n");
2549
        janus_request *request = (janus_request *)data;
2550
        if(request == NULL) {
2551
                JANUS_LOG(LOG_ERR, "Missing request\n");
2552
                return;
2553
        }
2554
        if(!request->admin)
2555
                janus_process_incoming_request(request);
2556
        else
2557
                janus_process_incoming_admin_request(request);
2558
        /* Done */
2559
        janus_request_destroy(request);
2560
}
2561

    
2562

    
2563
/* Event handlers */
2564
void janus_eventhandler_close(gpointer key, gpointer value, gpointer user_data) {
2565
        janus_eventhandler *eventhandler = (janus_eventhandler *)value;
2566
        if(!eventhandler)
2567
                return;
2568
        eventhandler->destroy();
2569
}
2570

    
2571
void janus_eventhandlerso_close(gpointer key, gpointer value, gpointer user_data) {
2572
        void *eventhandler = (janus_eventhandler *)value;
2573
        if(!eventhandler)
2574
                return;
2575
        //~ dlclose(eventhandler);
2576
}
2577

    
2578

    
2579
/* Plugins */
2580
void janus_plugin_close(gpointer key, gpointer value, gpointer user_data) {
2581
        janus_plugin *plugin = (janus_plugin *)value;
2582
        if(!plugin)
2583
                return;
2584
        plugin->destroy();
2585
}
2586

    
2587
void janus_pluginso_close(gpointer key, gpointer value, gpointer user_data) {
2588
        void *plugin = value;
2589
        if(!plugin)
2590
                return;
2591
        /* FIXME We don't dlclose plugins to be sure we can detect leaks */
2592
        //~ dlclose(plugin);
2593
}
2594

    
2595
janus_plugin *janus_plugin_find(const gchar *package) {
2596
        if(package != NULL && plugins != NULL)        /* FIXME Do we need to fix the key pointer? */
2597
                return g_hash_table_lookup(plugins, package);
2598
        return NULL;
2599
}
2600

    
2601

    
2602
/* Plugin callback interface */
2603
int janus_plugin_push_event(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *transaction, json_t *message, json_t *jsep) {
2604
        if(!plugin || !message)
2605
                return -1;
2606
        if(!plugin_session || plugin_session < (janus_plugin_session *)0x1000 ||
2607
                        !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped)
2608
                return -2;
2609
        janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
2610
        if(!ice_handle || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP))
2611
                return JANUS_ERROR_SESSION_NOT_FOUND;
2612
        janus_session *session = ice_handle->session;
2613
        if(!session || session->destroy)
2614
                return JANUS_ERROR_SESSION_NOT_FOUND;
2615
        /* Make sure this is a JSON object */
2616
        if(!json_is_object(message)) {
2617
                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Cannot push event (JSON error: not an object)\n", ice_handle->handle_id);
2618
                return JANUS_ERROR_INVALID_JSON_OBJECT;
2619
        }
2620
        /* Attach JSEP if possible? */
2621
        const char *sdp_type = json_string_value(json_object_get(jsep, "type"));
2622
        const char *sdp = json_string_value(json_object_get(jsep, "sdp"));
2623
        json_t *merged_jsep = NULL;
2624
        if(sdp_type != NULL && sdp != NULL) {
2625
                merged_jsep = janus_plugin_handle_sdp(plugin_session, plugin, sdp_type, sdp);
2626
                if(merged_jsep == NULL) {
2627
                        if(ice_handle == NULL || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
2628
                                        || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT)) {
2629
                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Cannot push event (handle not available anymore or negotiation stopped)\n", ice_handle->handle_id);
2630
                                return JANUS_ERROR_HANDLE_NOT_FOUND;
2631
                        } else {
2632
                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Cannot push event (JSON error: problem with the SDP)\n", ice_handle->handle_id);
2633
                                return JANUS_ERROR_JSEP_INVALID_SDP;
2634
                        }
2635
                }
2636
        }
2637
        /* Reference the payload, as the plugin may still need it and will do a decref itself */
2638
        json_incref(message);
2639
        /* Prepare JSON event */
2640
        json_t *event = json_object();
2641
        json_object_set_new(event, "janus", json_string("event"));
2642
        json_object_set_new(event, "session_id", json_integer(session->session_id));
2643
        json_object_set_new(event, "sender", json_integer(ice_handle->handle_id));
2644
        if(transaction != NULL)
2645
                json_object_set_new(event, "transaction", json_string(transaction));
2646
        json_t *plugin_data = json_object();
2647
        json_object_set_new(plugin_data, "plugin", json_string(plugin->get_package()));
2648
        json_object_set_new(plugin_data, "data", message);
2649
        json_object_set_new(event, "plugindata", plugin_data);
2650
        if(merged_jsep != NULL)
2651
                json_object_set_new(event, "jsep", merged_jsep);
2652
        /* Send the event */
2653
        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Sending event to transport...\n", ice_handle->handle_id);
2654
        janus_session_notify_event(session->session_id, event);
2655

    
2656
        if(jsep != NULL && janus_events_is_enabled()) {
2657
                /* Notify event handlers as well */
2658
                janus_events_notify_handlers(JANUS_EVENT_TYPE_JSEP,
2659
                        session->session_id, ice_handle->handle_id, "local", sdp_type, sdp);
2660
        }
2661

    
2662
        return JANUS_OK;
2663
}
2664

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

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

    
2993
        /* Prepare JSON event */
2994
        json_t *jsep = json_object();
2995
        json_object_set_new(jsep, "type", json_string(sdp_type));
2996
        json_object_set_new(jsep, "sdp", json_string(sdp_merged));
2997
        ice_handle->local_sdp = sdp_merged;
2998
        return jsep;
2999
}
3000

    
3001
void janus_plugin_relay_rtp(janus_plugin_session *plugin_session, int video, char *buf, int len) {
3002
        if((plugin_session < (janus_plugin_session *)0x1000) || plugin_session->stopped || buf == NULL || len < 1)
3003
                return;
3004
        janus_ice_handle *handle = (janus_ice_handle *)plugin_session->gateway_handle;
3005
        if(!handle || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
3006
                        || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
3007
                return;
3008
        janus_ice_relay_rtp(handle, video, buf, len);
3009
}
3010

    
3011
void janus_plugin_relay_rtcp(janus_plugin_session *plugin_session, int video, char *buf, int len) {
3012
        if((plugin_session < (janus_plugin_session *)0x1000) || plugin_session->stopped || buf == NULL || len < 1)
3013
                return;
3014
        janus_ice_handle *handle = (janus_ice_handle *)plugin_session->gateway_handle;
3015
        if(!handle || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
3016
                        || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
3017
                return;
3018
        janus_ice_relay_rtcp(handle, video, buf, len);
3019
}
3020

    
3021
void janus_plugin_relay_data(janus_plugin_session *plugin_session, char *buf, int len) {
3022
        if((plugin_session < (janus_plugin_session *)0x1000) || plugin_session->stopped || buf == NULL || len < 1)
3023
                return;
3024
        janus_ice_handle *handle = (janus_ice_handle *)plugin_session->gateway_handle;
3025
        if(!handle || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
3026
                        || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
3027
                return;
3028
#ifdef HAVE_SCTP
3029
        janus_ice_relay_data(handle, buf, len);
3030
#else
3031
        JANUS_LOG(LOG_WARN, "Asked to relay data, but Data Channels support has not been compiled...\n");
3032
#endif
3033
}
3034

    
3035
void janus_plugin_close_pc(janus_plugin_session *plugin_session) {
3036
        /* A plugin asked to get rid of a PeerConnection */
3037
        if((plugin_session < (janus_plugin_session *)0x1000) || !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped)
3038
                return;
3039
        janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
3040
        if(!ice_handle)
3041
                return;
3042
        if(janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
3043
                        || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
3044
                return;
3045
        janus_session *session = (janus_session *)ice_handle->session;
3046
        if(!session)
3047
                return;
3048

    
3049
        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Plugin asked to hangup PeerConnection: sending alert\n", ice_handle->handle_id);
3050
        /* Send an alert on all the DTLS connections */
3051
        janus_ice_webrtc_hangup(ice_handle);
3052
}
3053

    
3054
void janus_plugin_end_session(janus_plugin_session *plugin_session) {
3055
        /* A plugin asked to get rid of a handle */
3056
        if((plugin_session < (janus_plugin_session *)0x1000) || !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped)
3057
                return;
3058
        janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
3059
        if(!ice_handle)
3060
                return;
3061
        janus_session *session = (janus_session *)ice_handle->session;
3062
        if(!session)
3063
                return;
3064
        /* Destroy the handle */
3065
        janus_ice_handle_destroy(session, ice_handle->handle_id);
3066
        janus_mutex_lock(&session->mutex);
3067
        g_hash_table_remove(session->ice_handles, &ice_handle->handle_id);
3068
        janus_mutex_unlock(&session->mutex);
3069
}
3070

    
3071
void janus_plugin_notify_event(janus_plugin *plugin, janus_plugin_session *plugin_session, json_t *event) {
3072
        /* A plugin asked to notify an event to the handlers */
3073
        if(!plugin || !event || !json_is_object(event))
3074
                return;
3075
        guint64 session_id = 0, handle_id = 0;
3076
        if(plugin_session != NULL) {
3077
                if((plugin_session < (janus_plugin_session *)0x1000) || !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped) {
3078
                        json_decref(event);
3079
                        return;
3080
                }
3081
                janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
3082
                if(!ice_handle) {
3083
                        json_decref(event);
3084
                        return;
3085
                }
3086
                handle_id = ice_handle->handle_id;
3087
                janus_session *session = (janus_session *)ice_handle->session;
3088
                if(!session) {
3089
                        json_decref(event);
3090
                        return;
3091
                }
3092
                session_id = session->session_id;
3093
        }
3094
        /* Notify event handlers */
3095
        if(janus_events_is_enabled()) {
3096
                janus_events_notify_handlers(JANUS_EVENT_TYPE_PLUGIN,
3097
                        session_id, handle_id, plugin->get_package(), event);
3098
        } else {
3099
                json_decref(event);
3100
        }
3101
}
3102

    
3103

    
3104
static void janus_detect_local_ip(gchar *buf, size_t buflen) {
3105
        JANUS_LOG(LOG_VERB, "Autodetecting local IP...\n");
3106
        struct sockaddr_in addr;
3107
        socklen_t len;
3108
        int fd = socket(AF_INET, SOCK_DGRAM, 0);
3109
        if (fd == -1)
3110
                goto error;
3111
        addr.sin_family = AF_INET;
3112
        addr.sin_port = htons(1);
3113
        inet_pton(AF_INET, "1.2.3.4", &addr.sin_addr.s_addr);
3114
        if (connect(fd, (const struct sockaddr*) &addr, sizeof(addr)) < 0)
3115
                goto error;
3116
        len = sizeof(addr);
3117
        if (getsockname(fd, (struct sockaddr*) &addr, &len) < 0)
3118
                goto error;
3119
        if (getnameinfo((const struct sockaddr*) &addr, sizeof(addr),
3120
                        buf, buflen,
3121
                        NULL, 0, NI_NUMERICHOST) != 0)
3122
                goto error;
3123
        close(fd);
3124
        return;
3125
error:
3126
        if (fd != -1)
3127
                close(fd);
3128
        JANUS_LOG(LOG_VERB, "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");
3129
        g_strlcpy(buf, "127.0.0.1", buflen);
3130
}
3131

    
3132

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

    
3141
        struct gengetopt_args_info args_info;
3142
        /* Let's call our cmdline parser */
3143
        if(cmdline_parser(argc, argv, &args_info) != 0)
3144
                exit(1);
3145

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

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

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

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

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

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

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

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

    
3276
        /* Initialize logger */
3277
        if(janus_log_init(daemonize, use_stdout, logfile) < 0)
3278
                exit(1);
3279

    
3280
        JANUS_PRINT("---------------------------------------------------\n");
3281
        JANUS_PRINT("  Starting Meetecho Janus (WebRTC Gateway) v%s\n", JANUS_VERSION_STRING);
3282
        JANUS_PRINT("---------------------------------------------------\n\n");
3283

    
3284
        /* Handle SIGINT (CTRL-C), SIGTERM (from service managers) */
3285
        signal(SIGINT, janus_handle_signal);
3286
        signal(SIGTERM, janus_handle_signal);
3287
        atexit(janus_termination_handler);
3288

    
3289
        /* Setup Glib */
3290
#if !GLIB_CHECK_VERSION(2, 36, 0)
3291
        g_type_init();
3292
#endif
3293

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

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

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

    
3432
        /* Logging/debugging */
3433
        JANUS_PRINT("Debug/log level is %d\n", janus_log_level);
3434
        janus_config_item *item = janus_config_get_item_drilldown(config, "general", "debug_timestamps");
3435
        if(item && item->value)
3436
                janus_log_timestamps = janus_is_true(item->value);
3437
        JANUS_PRINT("Debug/log timestamps are %s\n", janus_log_timestamps ? "enabled" : "disabled");
3438
        item = janus_config_get_item_drilldown(config, "general", "debug_colors");
3439
        if(item && item->value)
3440
                janus_log_colors = janus_is_true(item->value);
3441
        JANUS_PRINT("Debug/log colors are %s\n", janus_log_colors ? "enabled" : "disabled");
3442

    
3443
        /* Any IP/interface to enforce/ignore? */
3444
        item = janus_config_get_item_drilldown(config, "nat", "ice_enforce_list");
3445
        if(item && item->value) {
3446
                gchar **list = g_strsplit(item->value, ",", -1);
3447
                gchar *index = list[0];
3448
                if(index != NULL) {
3449
                        int i=0;
3450
                        while(index != NULL) {
3451
                                if(strlen(index) > 0) {
3452
                                        JANUS_LOG(LOG_INFO, "Adding '%s' to the ICE enforce list...\n", index);
3453
                                        janus_ice_enforce_interface(g_strdup(index));
3454
                                }
3455
                                i++;
3456
                                index = list[i];
3457
                        }
3458
                }
3459
                g_clear_pointer(&list, g_strfreev);
3460
        }
3461
        item = janus_config_get_item_drilldown(config, "nat", "ice_ignore_list");
3462
        if(item && item->value) {
3463
                gchar **list = g_strsplit(item->value, ",", -1);
3464
                gchar *index = list[0];
3465
                if(index != NULL) {
3466
                        int i=0;
3467
                        while(index != NULL) {
3468
                                if(strlen(index) > 0) {
3469
                                        JANUS_LOG(LOG_INFO, "Adding '%s' to the ICE ignore list...\n", index);
3470
                                        janus_ice_ignore_interface(g_strdup(index));
3471
                                }
3472
                                i++;
3473
                                index = list[i];
3474
                        }
3475
                }
3476
                g_clear_pointer(&list, g_strfreev);
3477
        }
3478
        /* What is the local IP? */
3479
        JANUS_LOG(LOG_VERB, "Selecting local IP address...\n");
3480
        gboolean local_ip_set = FALSE;
3481
        item = janus_config_get_item_drilldown(config, "general", "interface");
3482
        if(item && item->value) {
3483
                JANUS_LOG(LOG_VERB, "  -- Will try to use %s\n", item->value);
3484
                int family;
3485
                if (!janus_is_ip_valid(item->value, &family)) {
3486
                        JANUS_LOG(LOG_WARN, "Invalid local IP specified: %s, guessing the default...\n", item->value);
3487
                } else {
3488
                        /* Verify that we can actually bind to that address */
3489
                        int fd = socket(family, SOCK_DGRAM, 0);
3490
                        if (fd == -1) {
3491
                                JANUS_LOG(LOG_WARN, "Error creating test socket, falling back to detecting IP address...\n");
3492
                        } else {
3493
                                int r;
3494
                                struct sockaddr_storage ss;
3495
                                socklen_t addrlen;
3496
                                memset(&ss, 0, sizeof(ss));
3497
                                if (family == AF_INET) {
3498
                                        struct sockaddr_in *addr4 = (struct sockaddr_in*)&ss;
3499
                                        addr4->sin_family = AF_INET;
3500
                                        addr4->sin_port = 0;
3501
                                        inet_pton(AF_INET, item->value, &(addr4->sin_addr.s_addr));
3502
                                        addrlen = sizeof(struct sockaddr_in);
3503
                                } else {
3504
                                        struct sockaddr_in6 *addr6 = (struct sockaddr_in6*)&ss;
3505
                                        addr6->sin6_family = AF_INET6;
3506
                                        addr6->sin6_port = 0;
3507
                                        inet_pton(AF_INET6, item->value, &(addr6->sin6_addr.s6_addr));
3508
                                        addrlen = sizeof(struct sockaddr_in6);
3509
                                }
3510
                                r = bind(fd, (const struct sockaddr*)&ss, addrlen);
3511
                                close(fd);
3512
                                if (r < 0) {
3513
                                        JANUS_LOG(LOG_WARN, "Error setting local IP address to %s, falling back to detecting IP address...\n", item->value);
3514
                                } else {
3515
                                        g_strlcpy(local_ip, item->value, sizeof(local_ip));
3516
                                        local_ip_set = TRUE;
3517
                                }
3518
                        }
3519
                }
3520
        }
3521
        if (!local_ip_set)
3522
                janus_detect_local_ip(local_ip, sizeof(local_ip));
3523
        JANUS_LOG(LOG_INFO, "Using %s as local IP...\n", local_ip);
3524

    
3525
        /* Was a custom instance name provided? */
3526
        item = janus_config_get_item_drilldown(config, "general", "server_name");
3527
        if(item && item->value) {
3528
                server_name = g_strdup(item->value);
3529
        }
3530

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

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

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

    
3713
        /* Setup OpenSSL stuff */
3714
        const char* server_pem;
3715
        item = janus_config_get_item_drilldown(config, "certificates", "cert_pem");
3716
        if(!item || !item->value) {
3717
                server_pem = NULL;
3718
        } else {
3719
                server_pem = item->value;
3720
        }
3721

    
3722
        const char* server_key;
3723
        item = janus_config_get_item_drilldown(config, "certificates", "cert_key");
3724
        if(!item || !item->value) {
3725
                server_key = NULL;
3726
        } else {
3727
                server_key = item->value;
3728
        }
3729
        JANUS_LOG(LOG_VERB, "Using certificates:\n\t%s\n\t%s\n", server_pem, server_key);
3730

    
3731
        SSL_library_init();
3732
        SSL_load_error_strings();
3733
        OpenSSL_add_all_algorithms();
3734
        /* ... and DTLS-SRTP in particular */
3735
        if(janus_dtls_srtp_init(server_pem, server_key) < 0) {
3736
                exit(1);
3737
        }
3738
        /* Check if there's any custom value for the starting MTU to use in the BIO filter */
3739
        item = janus_config_get_item_drilldown(config, "media", "dtls_mtu");
3740
        if(item && item->value)
3741
                janus_dtls_bio_filter_set_mtu(atoi(item->value));
3742

    
3743
#ifdef HAVE_SCTP
3744
        /* Initialize SCTP for DataChannels */
3745
        if(janus_sctp_init() < 0) {
3746
                exit(1);
3747
        }
3748
#else
3749
        JANUS_LOG(LOG_WARN, "Data Channels support not compiled\n");
3750
#endif
3751

    
3752
        /* Sessions */
3753
        sessions = g_hash_table_new_full(g_int64_hash, g_int64_equal, (GDestroyNotify)g_free, NULL);
3754
        old_sessions = g_hash_table_new_full(g_int64_hash, g_int64_equal, (GDestroyNotify)g_free, NULL);
3755
        janus_mutex_init(&sessions_mutex);
3756
        /* Start the sessions watchdog */
3757
        sessions_watchdog_context = g_main_context_new();
3758
        GMainLoop *watchdog_loop = g_main_loop_new(sessions_watchdog_context, FALSE);
3759
        GError *error = NULL;
3760
        GThread *watchdog = g_thread_try_new("sessions watchdog", &janus_sessions_watchdog, watchdog_loop, &error);
3761
        if(error != NULL) {
3762
                JANUS_LOG(LOG_FATAL, "Got error %d (%s) trying to start sessions watchdog...\n", error->code, error->message ? error->message : "??");
3763
                exit(1);
3764
        }
3765

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

    
3902
        /* Load plugins */
3903
        path = PLUGINDIR;
3904
        item = janus_config_get_item_drilldown(config, "general", "plugins_folder");
3905
        if(item && item->value)
3906
                path = (char *)item->value;
3907
        JANUS_LOG(LOG_INFO, "Plugins folder: %s\n", path);
3908
        dir = opendir(path);
3909
        if(!dir) {
3910
                JANUS_LOG(LOG_FATAL, "\tCouldn't access plugins folder...\n");
3911
                exit(1);
3912
        }
3913
        /* Any plugin to ignore? */
3914
        gchar **disabled_plugins = NULL;
3915
        item = janus_config_get_item_drilldown(config, "plugins", "disable");
3916
        if(item && item->value)
3917
                disabled_plugins = g_strsplit(item->value, ",", -1);
3918
        /* Open the shared objects */
3919
        struct dirent *pluginent = NULL;
3920
        char pluginpath[1024];
3921
        while((pluginent = readdir(dir))) {
3922
                int len = strlen(pluginent->d_name);
3923
                if (len < 4) {
3924
                        continue;
3925
                }
3926
                if (strcasecmp(pluginent->d_name+len-strlen(SHLIB_EXT), SHLIB_EXT)) {
3927
                        continue;
3928
                }
3929
                /* Check if this plugins has been disabled in the configuration file */
3930
                if(disabled_plugins != NULL) {
3931
                        gchar *index = disabled_plugins[0];
3932
                        if(index != NULL) {
3933
                                int i=0;
3934
                                gboolean skip = FALSE;
3935
                                while(index != NULL) {
3936
                                        while(isspace(*index))
3937
                                                index++;
3938
                                        if(strlen(index) && !strcmp(index, pluginent->d_name)) {
3939
                                                JANUS_LOG(LOG_WARN, "Plugin '%s' has been disabled, skipping...\n", pluginent->d_name);
3940
                                                skip = TRUE;
3941
                                                break;
3942
                                        }
3943
                                        i++;
3944
                                        index = disabled_plugins[i];
3945
                                }
3946
                                if(skip)
3947
                                        continue;
3948
                        }
3949
                }
3950
                JANUS_LOG(LOG_INFO, "Loading plugin '%s'...\n", pluginent->d_name);
3951
                memset(pluginpath, 0, 1024);
3952
                g_snprintf(pluginpath, 1024, "%s/%s", path, pluginent->d_name);
3953
                void *plugin = dlopen(pluginpath, RTLD_LOCAL | RTLD_LAZY);
3954
                if (!plugin) {
3955
                        JANUS_LOG(LOG_ERR, "\tCouldn't load plugin '%s': %s\n", pluginent->d_name, dlerror());
3956
                } else {
3957
                        create_p *create = (cr