Statistics
| Branch: | Revision:

janus-gateway / janus.c @ becc0c84

History | View | Annotate | Download (177 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 "record.h"
37
#include "events.h"
38

    
39

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

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

    
52

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

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

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

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

    
66

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

    
71

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

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

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

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

    
130

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

    
153

    
154
/* Public instance name */
155
static gchar *server_name = NULL;
156

    
157

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

    
262
        return info;
263
}
264

    
265

    
266
/* Logging */
267
int janus_log_level = LOG_INFO;
268
gboolean janus_log_timestamps = FALSE;
269
gboolean janus_log_colors = FALSE;
270
int lock_debug = 0;
271

    
272

    
273
/*! \brief Signal handler (just used to intercept CTRL+C and SIGTERM) */
274
static void janus_handle_signal(int signum) {
275
        stop_signal = signum;
276
        switch(g_atomic_int_get(&stop)) {
277
                case 0:
278
                        JANUS_PRINT("Stopping gateway, please wait...\n");
279
                        break;
280
                case 1:
281
                        JANUS_PRINT("In a hurry? I'm trying to free resources cleanly, here!\n");
282
                        break;
283
                default:
284
                        JANUS_PRINT("Ok, leaving immediately...\n");
285
                        break;
286
        }
287
        g_atomic_int_inc(&stop);
288
        if(g_atomic_int_get(&stop) > 2)
289
                exit(1);
290
}
291

    
292
/*! \brief Termination handler (atexit) */
293
static void janus_termination_handler(void) {
294
        /* Free the instance name, if provided */
295
        g_free(server_name);
296
        /* Remove the PID file if we created it */
297
        janus_pidfile_remove();
298
        /* Close the logger */
299
        janus_log_destroy();
300
        /* If we're daemonizing, we send an error code to the parent */
301
        if(daemonize) {
302
                int code = 1;
303
                ssize_t res = 0;
304
                do {
305
                        res = write(pipefd[1], &code, sizeof(int));
306
                } while(res == -1 && errno == EINTR);
307
        }
308
}
309

    
310

    
311
/** @name Transport plugin callback interface
312
 * These are the callbacks implemented by the gateway core, as part of
313
 * the janus_transport_callbacks interface. Everything the transport
314
 * plugins send the gateway is handled here.
315
 */
316
///@{
317
void janus_transport_incoming_request(janus_transport *plugin, void *transport, void *request_id, gboolean admin, json_t *message, json_error_t *error);
318
void janus_transport_gone(janus_transport *plugin, void *transport);
319
gboolean janus_transport_is_api_secret_needed(janus_transport *plugin);
320
gboolean janus_transport_is_api_secret_valid(janus_transport *plugin, const char *apisecret);
321
gboolean janus_transport_is_auth_token_needed(janus_transport *plugin);
322
gboolean janus_transport_is_auth_token_valid(janus_transport *plugin, const char *token);
323
void janus_transport_notify_event(janus_transport *plugin, void *transport, json_t *event);
324

    
325
static janus_transport_callbacks janus_handler_transport =
326
        {
327
                .incoming_request = janus_transport_incoming_request,
328
                .transport_gone = janus_transport_gone,
329
                .is_api_secret_needed = janus_transport_is_api_secret_needed,
330
                .is_api_secret_valid = janus_transport_is_api_secret_valid,
331
                .is_auth_token_needed = janus_transport_is_auth_token_needed,
332
                .is_auth_token_valid = janus_transport_is_auth_token_valid,
333
                .events_is_enabled = janus_events_is_enabled,
334
                .notify_event = janus_transport_notify_event,
335
        };
336
GThreadPool *tasks = NULL;
337
void janus_transport_task(gpointer data, gpointer user_data);
338
///@}
339

    
340

    
341
/** @name Plugin callback interface
342
 * These are the callbacks implemented by the gateway core, as part of
343
 * the janus_callbacks interface. Everything the plugins send the
344
 * gateway is handled here.
345
 */
346
///@{
347
int janus_plugin_push_event(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *transaction, json_t *message, json_t *jsep);
348
json_t *janus_plugin_handle_sdp(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *sdp_type, const char *sdp);
349
void janus_plugin_relay_rtp(janus_plugin_session *plugin_session, int video, char *buf, int len);
350
void janus_plugin_relay_rtcp(janus_plugin_session *plugin_session, int video, char *buf, int len);
351
void janus_plugin_relay_data(janus_plugin_session *plugin_session, char *buf, int len);
352
void janus_plugin_close_pc(janus_plugin_session *plugin_session);
353
void janus_plugin_end_session(janus_plugin_session *plugin_session);
354
void janus_plugin_notify_event(janus_plugin *plugin, janus_plugin_session *plugin_session, json_t *event);
355
static janus_callbacks janus_handler_plugin =
356
        {
357
                .push_event = janus_plugin_push_event,
358
                .relay_rtp = janus_plugin_relay_rtp,
359
                .relay_rtcp = janus_plugin_relay_rtcp,
360
                .relay_data = janus_plugin_relay_data,
361
                .close_pc = janus_plugin_close_pc,
362
                .end_session = janus_plugin_end_session,
363
                .events_is_enabled = janus_events_is_enabled,
364
                .notify_event = janus_plugin_notify_event,
365
        }; 
366
///@}
367

    
368

    
369
/* Gateway Sessions */
370
static janus_mutex sessions_mutex;
371
static GHashTable *sessions = NULL, *old_sessions = NULL;
372
static GMainContext *sessions_watchdog_context = NULL;
373

    
374

    
375
#define SESSION_TIMEOUT                60                /* FIXME Should this be higher, e.g., 120 seconds? */
376

    
377
static gboolean janus_cleanup_session(gpointer user_data) {
378
        janus_session *session = (janus_session *) user_data;
379

    
380
        JANUS_LOG(LOG_DBG, "Cleaning up session %"SCNu64"...\n", session->session_id);
381
        janus_session_destroy(session->session_id);
382

    
383
        return G_SOURCE_REMOVE;
384
}
385

    
386
static gboolean janus_check_sessions(gpointer user_data) {
387
        GMainContext *watchdog_context = (GMainContext *) user_data;
388
        janus_mutex_lock(&sessions_mutex);
389
        if(sessions && g_hash_table_size(sessions) > 0) {
390
                GHashTableIter iter;
391
                gpointer value;
392
                g_hash_table_iter_init(&iter, sessions);
393
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
394
                        janus_session *session = (janus_session *) value;
395
                        if (!session || session->destroy) {
396
                                continue;
397
                        }
398
                        gint64 now = janus_get_monotonic_time();
399
                        if (now - session->last_activity >= SESSION_TIMEOUT * G_USEC_PER_SEC && !session->timeout) {
400
                                JANUS_LOG(LOG_INFO, "Timeout expired for session %"SCNu64"...\n", session->session_id);
401

    
402
                                /* Notify the transport */
403
                                if(session->source) {
404
                                        json_t *event = json_object();
405
                                        json_object_set_new(event, "janus", json_string("timeout"));
406
                                        json_object_set_new(event, "session_id", json_integer(session->session_id));
407
                                        /* Send this to the transport client */
408
                                        session->source->transport->send_message(session->source->instance, NULL, FALSE, event);
409
                                        /* Notify the transport plugin about the session timeout */
410
                                        session->source->transport->session_over(session->source->instance, session->session_id, TRUE);
411
                                }
412
                                /* Notify event handlers as well */
413
                                if(janus_events_is_enabled())
414
                                        janus_events_notify_handlers(JANUS_EVENT_TYPE_SESSION, session->session_id, "timeout", NULL);
415

    
416
                                /* Mark the session as over, we'll deal with it later */
417
                                session->timeout = 1;
418
                                /* FIXME Is this safe? apparently it causes hash table errors on the console */
419
                                g_hash_table_iter_remove(&iter);
420
                                g_hash_table_insert(old_sessions, janus_uint64_dup(session->session_id), session);
421

    
422
                                /* Schedule the session for deletion */
423
                                GSource *timeout_source = g_timeout_source_new_seconds(3);
424
                                g_source_set_callback(timeout_source, janus_cleanup_session, session, NULL);
425
                                g_source_attach(timeout_source, watchdog_context);
426
                                g_source_unref(timeout_source);
427
                        }
428
                }
429
        }
430
        janus_mutex_unlock(&sessions_mutex);
431

    
432
        return G_SOURCE_CONTINUE;
433
}
434

    
435
static gpointer janus_sessions_watchdog(gpointer user_data) {
436
        GMainLoop *loop = (GMainLoop *) user_data;
437
        GMainContext *watchdog_context = g_main_loop_get_context(loop);
438
        GSource *timeout_source;
439

    
440
        timeout_source = g_timeout_source_new_seconds(2);
441
        g_source_set_callback(timeout_source, janus_check_sessions, watchdog_context, NULL);
442
        g_source_attach(timeout_source, watchdog_context);
443
        g_source_unref(timeout_source);
444

    
445
        JANUS_LOG(LOG_INFO, "Sessions watchdog started\n");
446

    
447
        g_main_loop_run(loop);
448

    
449
        return NULL;
450
}
451

    
452
janus_session *janus_session_create(guint64 session_id) {
453
        if(session_id == 0) {
454
                while(session_id == 0) {
455
                        session_id = janus_random_uint64();
456
                        if(janus_session_find(session_id) != NULL) {
457
                                /* Session ID already taken, try another one */
458
                                session_id = 0;
459
                        }
460
                }
461
        }
462
        JANUS_LOG(LOG_INFO, "Creating new session: %"SCNu64"\n", session_id);
463
        janus_session *session = (janus_session *)g_malloc0(sizeof(janus_session));
464
        if(session == NULL) {
465
                JANUS_LOG(LOG_FATAL, "Memory error!\n");
466
                return NULL;
467
        }
468
        session->session_id = session_id;
469
        session->source = NULL;
470
        session->destroy = 0;
471
        session->timeout = 0;
472
        session->last_activity = janus_get_monotonic_time();
473
        janus_mutex_init(&session->mutex);
474
        janus_mutex_lock(&sessions_mutex);
475
        g_hash_table_insert(sessions, janus_uint64_dup(session->session_id), session);
476
        janus_mutex_unlock(&sessions_mutex);
477
        return session;
478
}
479

    
480
janus_session *janus_session_find(guint64 session_id) {
481
        janus_mutex_lock(&sessions_mutex);
482
        janus_session *session = g_hash_table_lookup(sessions, &session_id);
483
        janus_mutex_unlock(&sessions_mutex);
484
        return session;
485
}
486

    
487
janus_session *janus_session_find_destroyed(guint64 session_id) {
488
        janus_mutex_lock(&sessions_mutex);
489
        janus_session *session = g_hash_table_lookup(old_sessions, &session_id);
490
        janus_mutex_unlock(&sessions_mutex);
491
        return session;
492
}
493

    
494
void janus_session_notify_event(guint64 session_id, json_t *event) {
495
        janus_mutex_lock(&sessions_mutex);
496
        janus_session *session = sessions ? g_hash_table_lookup(sessions, &session_id) : NULL;
497
        if(session != NULL && !session->destroy && session->source != NULL && session->source->transport != NULL) {
498
                janus_mutex_unlock(&sessions_mutex);
499
                /* Send this to the transport client */
500
                JANUS_LOG(LOG_HUGE, "Sending event to %s (%p)\n", session->source->transport->get_package(), session->source->instance);
501
                session->source->transport->send_message(session->source->instance, NULL, FALSE, event);
502
        } else {
503
                janus_mutex_unlock(&sessions_mutex);
504
                /* No transport, free the event */
505
                json_decref(event);
506
        }
507
}
508

    
509

    
510
/* Destroys a session but does not remove it from the sessions hash table. */
511
gint janus_session_destroy(guint64 session_id) {
512
        janus_session *session = janus_session_find_destroyed(session_id);
513
        if(session == NULL) {
514
                JANUS_LOG(LOG_ERR, "Couldn't find session to destroy: %"SCNu64"\n", session_id);
515
                return -1;
516
        }
517
        JANUS_LOG(LOG_VERB, "Destroying session %"SCNu64"\n", session_id);
518
        session->destroy = 1;
519
        if (session->ice_handles != NULL && g_hash_table_size(session->ice_handles) > 0) {
520
                GHashTableIter iter;
521
                gpointer value;
522
                /* Remove all handles */
523
                g_hash_table_iter_init(&iter, session->ice_handles);
524
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
525
                        janus_ice_handle *handle = value;
526
                        if(!handle || g_atomic_int_get(&stop)) {
527
                                continue;
528
                        }
529
                        janus_ice_handle_destroy(session, handle->handle_id);
530
                        g_hash_table_iter_remove(&iter);
531
                }
532
        }
533

    
534
        /* FIXME Actually destroy session */
535
        janus_session_free(session);
536

    
537
        return 0;
538
}
539

    
540
void janus_session_free(janus_session *session) {
541
        if(session == NULL)
542
                return;
543
        janus_mutex_lock(&session->mutex);
544
        if(session->ice_handles != NULL) {
545
                g_hash_table_destroy(session->ice_handles);
546
                session->ice_handles = NULL;
547
        }
548
        if(session->source != NULL) {
549
                janus_request_destroy(session->source);
550
                session->source = NULL;
551
        }
552
        janus_mutex_unlock(&session->mutex);
553
        g_free(session);
554
        session = NULL;
555
}
556

    
557

    
558
/* Requests management */
559
janus_request *janus_request_new(janus_transport *transport, void *instance, void *request_id, gboolean admin, json_t *message) {
560
        janus_request *request = (janus_request *)g_malloc0(sizeof(janus_request));
561
        request->transport = transport;
562
        request->instance = instance;
563
        request->request_id = request_id;
564
        request->admin = admin;
565
        request->message = message;
566
        return request;
567
}
568

    
569
void janus_request_destroy(janus_request *request) {
570
        if(request == NULL)
571
                return;
572
        request->transport = NULL;
573
        request->instance = NULL;
574
        request->request_id = NULL;
575
        if(request->message)
576
                json_decref(request->message);
577
        request->message = NULL;
578
        g_free(request);
579
}
580

    
581
int janus_process_incoming_request(janus_request *request) {
582
        int ret = -1;
583
        if(request == NULL) {
584
                JANUS_LOG(LOG_ERR, "Missing request or payload to process, giving up...\n");
585
                return ret;
586
        }
587
        int error_code = 0;
588
        char error_cause[100];
589
        json_t *root = request->message;
590
        /* Ok, let's start with the ids */
591
        guint64 session_id = 0, handle_id = 0;
592
        json_t *s = json_object_get(root, "session_id");
593
        if(s && json_is_integer(s))
594
                session_id = json_integer_value(s);
595
        json_t *h = json_object_get(root, "handle_id");
596
        if(h && json_is_integer(h))
597
                handle_id = json_integer_value(h);
598

    
599
        /* Get transaction and message request */
600
        JANUS_VALIDATE_JSON_OBJECT(root, incoming_request_parameters,
601
                error_code, error_cause, FALSE,
602
                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
603
        if(error_code != 0) {
604
                ret = janus_process_error_string(request, session_id, NULL, error_code, error_cause);
605
                goto jsondone;
606
        }
607
        json_t *transaction = json_object_get(root, "transaction");
608
        const gchar *transaction_text = json_string_value(transaction);
609
        json_t *message = json_object_get(root, "janus");
610
        const gchar *message_text = json_string_value(message);
611

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

    
712
        /* Go on with the processing */
713
        gboolean secret_authorized = FALSE, token_authorized = FALSE;
714
        if(api_secret == NULL && !janus_auth_is_enabled()) {
715
                /* Nothing to check */
716
                secret_authorized = TRUE;
717
                token_authorized = TRUE;
718
        } else {
719
                if(api_secret != NULL) {
720
                        /* There's an API secret, check that the client provided it */
721
                        json_t *secret = json_object_get(root, "apisecret");
722
                        if(secret && json_is_string(secret) && janus_strcmp_const_time(json_string_value(secret), api_secret)) {
723
                                secret_authorized = TRUE;
724
                        }
725
                }
726
                if(janus_auth_is_enabled()) {
727
                        /* The token based authentication mechanism is enabled, check that the client provided it */
728
                        json_t *token = json_object_get(root, "token");
729
                        if(token && json_is_string(token) && janus_auth_check_token(json_string_value(token))) {
730
                                token_authorized = TRUE;
731
                        }
732
                }
733
                /* We consider a request authorized if either the proper API secret or a valid token has been provided */
734
                if(!secret_authorized && !token_authorized) {
735
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNAUTHORIZED, NULL);
736
                        goto jsondone;
737
                }
738
        }
739

    
740
        /* If we got here, make sure we have a session (and/or a handle) */
741
        janus_session *session = janus_session_find(session_id);
742
        if(!session) {
743
                JANUS_LOG(LOG_ERR, "Couldn't find any session %"SCNu64"...\n", session_id);
744
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, "No such session %"SCNu64"", session_id);
745
                goto jsondone;
746
        }
747
        /* Update the last activity timer */
748
        session->last_activity = janus_get_monotonic_time();
749
        janus_ice_handle *handle = NULL;
750
        if(handle_id > 0) {
751
                handle = janus_ice_handle_find(session, handle_id);
752
                if(!handle) {
753
                        JANUS_LOG(LOG_ERR, "Couldn't find any handle %"SCNu64" in session %"SCNu64"...\n", handle_id, session_id);
754
                        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);
755
                        goto jsondone;
756
                }
757
        }
758

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

    
852
                /* Prepare JSON reply */
853
                json_t *reply = json_object();
854
                json_object_set_new(reply, "janus", json_string("success"));
855
                json_object_set_new(reply, "session_id", json_integer(session_id));
856
                json_object_set_new(reply, "transaction", json_string(transaction_text));
857
                /* Send the success reply */
858
                ret = janus_process_success(request, reply);
859
                /* Notify event handlers as well */
860
                if(janus_events_is_enabled())
861
                        janus_events_notify_handlers(JANUS_EVENT_TYPE_SESSION, session_id, "destroyed", NULL);
862
        } else if(!strcasecmp(message_text, "detach")) {
863
                if(handle == NULL) {
864
                        /* Query is an handle-level command */
865
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
866
                        goto jsondone;
867
                }
868
                if(handle->app == NULL || handle->app_handle == NULL) {
869
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_DETACH, "No plugin to detach from");
870
                        goto jsondone;
871
                }
872
                int error = janus_ice_handle_destroy(session, handle_id);
873
                janus_mutex_lock(&session->mutex);
874
                g_hash_table_remove(session->ice_handles, &handle_id);
875
                janus_mutex_unlock(&session->mutex);
876

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

    
1304
                /* Make sure the app handle is still valid */
1305
                if(handle->app == NULL || handle->app_handle == NULL || !janus_plugin_session_is_alive(handle->app_handle)) {
1306
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE, "No plugin to handle this message");
1307
                        g_free(jsep_type);
1308
                        g_free(jsep_sdp_stripped);
1309
                        janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
1310
                        goto jsondone;
1311
                }
1312

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

    
1450
trickledone:
1451
                janus_mutex_unlock(&handle->mutex);
1452
                /* We reply right away, not to block the web server... */
1453
                json_t *reply = json_object();
1454
                json_object_set_new(reply, "janus", json_string("ack"));
1455
                json_object_set_new(reply, "session_id", json_integer(session_id));
1456
                json_object_set_new(reply, "transaction", json_string(transaction_text));
1457
                /* Send the success reply */
1458
                ret = janus_process_success(request, reply);
1459
        } else {
1460
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN_REQUEST, "Unknown request '%s'", message_text);
1461
        }
1462

    
1463
jsondone:
1464
        /* Done processing */
1465
        return ret;
1466
}
1467

    
1468
/* Admin/monitor WebServer requests handler */
1469
int janus_process_incoming_admin_request(janus_request *request) {
1470
        int ret = -1;
1471
        int error_code = 0;
1472
        char error_cause[100];
1473
        if(request == NULL) {
1474
                JANUS_LOG(LOG_ERR, "Missing request or payload to process, giving up...\n");
1475
                return ret;
1476
        }
1477
        json_t *root = request->message;
1478
        /* Ok, let's start with the ids */
1479
        guint64 session_id = 0, handle_id = 0;
1480
        json_t *s = json_object_get(root, "session_id");
1481
        if(s && json_is_integer(s))
1482
                session_id = json_integer_value(s);
1483
        json_t *h = json_object_get(root, "handle_id");
1484
        if(h && json_is_integer(h))
1485
                handle_id = json_integer_value(h);
1486

    
1487
        /* Get transaction and message request */
1488
        JANUS_VALIDATE_JSON_OBJECT(root, admin_parameters,
1489
                error_code, error_cause, FALSE,
1490
                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
1491
        if(error_code != 0) {
1492
                ret = janus_process_error_string(request, session_id, NULL, error_code, error_cause);
1493
                goto jsondone;
1494
        }
1495
        json_t *transaction = json_object_get(root, "transaction");
1496
        const gchar *transaction_text = json_string_value(transaction);
1497
        json_t *message = json_object_get(root, "janus");
1498
        if(!message) {
1499
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_MISSING_MANDATORY_ELEMENT, "Missing mandatory element (janus)");
1500
                goto jsondone;
1501
        }
1502
        if(!json_is_string(message)) {
1503
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_ELEMENT_TYPE, "Invalid element type (janus should be a string)");
1504
                goto jsondone;
1505
        }
1506
        const gchar *message_text = json_string_value(message);
1507

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

    
2030
        /* Go on with the processing */
2031
        if(admin_api_secret != NULL) {
2032
                /* There's an API secret, check that the client provided it */
2033
                json_t *secret = json_object_get(root, "admin_secret");
2034
                if(!secret || !json_is_string(secret) || !janus_strcmp_const_time(json_string_value(secret), admin_api_secret)) {
2035
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNAUTHORIZED, NULL);
2036
                        goto jsondone;
2037
                }
2038
        }
2039

    
2040
        /* If we got here, make sure we have a session (and/or a handle) */
2041
        janus_session *session = janus_session_find(session_id);
2042
        if(!session) {
2043
                JANUS_LOG(LOG_ERR, "Couldn't find any session %"SCNu64"...\n", session_id);
2044
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, "No such session %"SCNu64"", session_id);
2045
                goto jsondone;
2046
        }
2047
        janus_ice_handle *handle = NULL;
2048
        if(handle_id > 0) {
2049
                handle = janus_ice_handle_find(session, handle_id);
2050
                if(!handle) {
2051
                        JANUS_LOG(LOG_ERR, "Couldn't find any handle %"SCNu64" in session %"SCNu64"...\n", handle_id, session_id);
2052
                        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);
2053
                        goto jsondone;
2054
                }
2055
        }
2056

    
2057
        /* What is this? */
2058
        if(handle == NULL) {
2059
                /* Session-related */
2060
                if(strcasecmp(message_text, "list_handles")) {
2061
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
2062
                        goto jsondone;
2063
                }
2064
                /* List handles */
2065
                json_t *list = json_array();
2066
                if(session->ice_handles != NULL && g_hash_table_size(session->ice_handles) > 0) {
2067
                        GHashTableIter iter;
2068
                        gpointer value;
2069
                        janus_mutex_lock(&session->mutex);
2070
                        g_hash_table_iter_init(&iter, session->ice_handles);
2071
                        while (g_hash_table_iter_next(&iter, NULL, &value)) {
2072
                                janus_ice_handle *handle = value;
2073
                                if(handle == NULL) {
2074
                                        continue;
2075
                                }
2076
                                json_array_append_new(list, json_integer(handle->handle_id));
2077
                        }
2078
                        janus_mutex_unlock(&session->mutex);
2079
                }
2080
                /* Prepare JSON reply */
2081
                json_t *reply = json_object();
2082
                json_object_set_new(reply, "janus", json_string("success"));
2083
                json_object_set_new(reply, "transaction", json_string(transaction_text));
2084
                json_object_set_new(reply, "session_id", json_integer(session_id));
2085
                json_object_set_new(reply, "handles", list);
2086
                /* Send the success reply */
2087
                ret = janus_process_success(request, reply);
2088
                goto jsondone;
2089
        } else {
2090
                /* Handle-related */
2091
                if(strcasecmp(message_text, "handle_info")) {
2092
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
2093
                        goto jsondone;
2094
                }
2095
                /* Prepare info */
2096
                janus_mutex_lock(&handle->mutex);
2097
                json_t *info = json_object();
2098
                json_object_set_new(info, "session_id", json_integer(session_id));
2099
                json_object_set_new(info, "session_last_activity", json_integer(session->last_activity));
2100
                if(session->source && session->source->transport)
2101
                        json_object_set_new(info, "session_transport", json_string(session->source->transport->get_package()));
2102
                json_object_set_new(info, "handle_id", json_integer(handle_id));
2103
                if(handle->opaque_id)
2104
                        json_object_set_new(info, "opaque_id", json_string(handle->opaque_id));
2105
                json_object_set_new(info, "created", json_integer(handle->created));
2106
                json_object_set_new(info, "send_thread_created", g_atomic_int_get(&handle->send_thread_created) ? json_true() : json_false());
2107
                json_object_set_new(info, "current_time", json_integer(janus_get_monotonic_time()));
2108
                if(handle->app && handle->app_handle && janus_plugin_session_is_alive(handle->app_handle)) {
2109
                        janus_plugin *plugin = (janus_plugin *)handle->app;
2110
                        json_object_set_new(info, "plugin", json_string(plugin->get_package()));
2111
                        if(plugin->query_session) {
2112
                                /* FIXME This check will NOT work with legacy plugins that were compiled BEFORE the method was specified in plugin.h */
2113
                                json_t *query = plugin->query_session(handle->app_handle);
2114
                                if(query != NULL) {
2115
                                        /* Make sure this is a JSON object */
2116
                                        if(!json_is_object(query)) {
2117
                                                JANUS_LOG(LOG_WARN, "Ignoring invalid query response from the plugin (not an object)\n");
2118
                                                json_decref(query);
2119
                                        } else {
2120
                                                json_object_set_new(info, "plugin_specific", query);
2121
                                        }
2122
                                        query = NULL;
2123
                                }
2124
                        }
2125
                }
2126
                json_t *flags = json_object();
2127
                json_object_set_new(flags, "got-offer", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_OFFER) ? json_true() : json_false());
2128
                json_object_set_new(flags, "got-answer", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_ANSWER) ? json_true() : json_false());
2129
                json_object_set_new(flags, "processing-offer", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER) ? json_true() : json_false());
2130
                json_object_set_new(flags, "starting", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_START) ? json_true() : json_false());
2131
                json_object_set_new(flags, "ready", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_READY) ? json_true() : json_false());
2132
                json_object_set_new(flags, "stopped", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP) ? json_true() : json_false());
2133
                json_object_set_new(flags, "alert", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT) ? json_true() : json_false());
2134
                json_object_set_new(flags, "bundle", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE) ? json_true() : json_false());
2135
                json_object_set_new(flags, "rtcp-mux", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_RTCPMUX) ? json_true() : json_false());
2136
                json_object_set_new(flags, "trickle", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_TRICKLE) ? json_true() : json_false());
2137
                json_object_set_new(flags, "all-trickles", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALL_TRICKLES) ? json_true() : json_false());
2138
                json_object_set_new(flags, "trickle-synced", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_TRICKLE_SYNCED) ? json_true() : json_false());
2139
                json_object_set_new(flags, "data-channels", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_DATA_CHANNELS) ? json_true() : json_false());
2140
                json_object_set_new(flags, "has-audio", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_AUDIO) ? json_true() : json_false());
2141
                json_object_set_new(flags, "has-video", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_VIDEO) ? json_true() : json_false());
2142
                json_object_set_new(flags, "plan-b", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PLAN_B) ? json_true() : json_false());
2143
                json_object_set_new(flags, "cleaning", janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_CLEANING) ? json_true() : json_false());
2144
                json_object_set_new(info, "flags", flags);
2145
                if(handle->agent) {
2146
                        json_object_set_new(info, "agent-created", json_integer(handle->agent_created));
2147
                        json_object_set_new(info, "ice-mode", json_string(janus_ice_is_ice_lite_enabled() ? "lite" : "full"));
2148
                        json_object_set_new(info, "ice-role", json_string(handle->controlling ? "controlling" : "controlled"));
2149
                }
2150
                json_t *sdps = json_object();
2151
                if(handle->rtp_profile)
2152
                        json_object_set_new(sdps, "profile", json_string(handle->rtp_profile));
2153
                if(handle->local_sdp)
2154
                        json_object_set_new(sdps, "local", json_string(handle->local_sdp));
2155
                if(handle->remote_sdp)
2156
                        json_object_set_new(sdps, "remote", json_string(handle->remote_sdp));
2157
                json_object_set_new(info, "sdps", sdps);
2158
                if(handle->pending_trickles)
2159
                        json_object_set_new(info, "pending-trickles", json_integer(g_list_length(handle->pending_trickles)));
2160
                if(handle->queued_packets)
2161
                        json_object_set_new(info, "queued-packets", json_integer(g_async_queue_length(handle->queued_packets)));
2162
                json_t *streams = json_array();
2163
                if(handle->audio_stream) {
2164
                        json_t *s = janus_admin_stream_summary(handle->audio_stream);
2165
                        if(s)
2166
                                json_array_append_new(streams, s);
2167
                }
2168
                if(handle->video_stream) {
2169
                        json_t *s = janus_admin_stream_summary(handle->video_stream);
2170
                        if(s)
2171
                                json_array_append_new(streams, s);
2172
                }
2173
                if(handle->data_stream) {
2174
                        json_t *s = janus_admin_stream_summary(handle->data_stream);
2175
                        if(s)
2176
                                json_array_append_new(streams, s);
2177
                }
2178
                json_object_set_new(info, "streams", streams);
2179
                janus_mutex_unlock(&handle->mutex);
2180
                /* Prepare JSON reply */
2181
                json_t *reply = json_object();
2182
                json_object_set_new(reply, "janus", json_string("success"));
2183
                json_object_set_new(reply, "transaction", json_string(transaction_text));
2184
                json_object_set_new(reply, "session_id", json_integer(session_id));
2185
                json_object_set_new(reply, "handle_id", json_integer(handle_id));
2186
                json_object_set_new(reply, "info", info);
2187
                /* Send the success reply */
2188
                ret = janus_process_success(request, reply);
2189
                goto jsondone;
2190
        }
2191

    
2192
jsondone:
2193
        /* Done processing */
2194
        return ret;
2195
}
2196

    
2197
int janus_process_success(janus_request *request, json_t *payload)
2198
{
2199
        if(!request || !payload)
2200
                return -1;
2201
        /* Pass to the right transport plugin */
2202
        JANUS_LOG(LOG_HUGE, "Sending %s API response to %s (%p)\n", request->admin ? "admin" : "Janus", request->transport->get_package(), request->instance);
2203
        return request->transport->send_message(request->instance, request->request_id, request->admin, payload);
2204
}
2205

    
2206
static int janus_process_error_string(janus_request *request, uint64_t session_id, const char *transaction, gint error, gchar *error_string)
2207
{
2208
        if(!request)
2209
                return -1;
2210
        /* Done preparing error */
2211
        JANUS_LOG(LOG_VERB, "[%s] Returning %s API error %d (%s)\n", transaction, request->admin ? "admin" : "Janus", error, error_string);
2212
        /* Prepare JSON error */
2213
        json_t *reply = json_object();
2214
        json_object_set_new(reply, "janus", json_string("error"));
2215
        if(session_id > 0)
2216
                json_object_set_new(reply, "session_id", json_integer(session_id));
2217
        if(transaction != NULL)
2218
                json_object_set_new(reply, "transaction", json_string(transaction));
2219
        json_t *error_data = json_object();
2220
        json_object_set_new(error_data, "code", json_integer(error));
2221
        json_object_set_new(error_data, "reason", json_string(error_string));
2222
        json_object_set_new(reply, "error", error_data);
2223
        /* Pass to the right transport plugin */
2224
        return request->transport->send_message(request->instance, request->request_id, request->admin, reply);
2225
}
2226

    
2227
int janus_process_error(janus_request *request, uint64_t session_id, const char *transaction, gint error, const char *format, ...)
2228
{
2229
        if(!request)
2230
                return -1;
2231
        gchar *error_string = NULL;
2232
        gchar error_buf[512];
2233
        if(format == NULL) {
2234
                /* No error string provided, use the default one */
2235
                error_string = (gchar *)janus_get_api_error(error);
2236
        } else {
2237
                /* This callback has variable arguments (error string) */
2238
                va_list ap;
2239
                va_start(ap, format);
2240
                g_vsnprintf(error_buf, sizeof(error_buf), format, ap);
2241
                va_end(ap);
2242
                error_string = error_buf;
2243
        }
2244
        return janus_process_error_string(request, session_id, transaction, error, error_string);
2245
}
2246

    
2247
/* Admin/monitor helpers */
2248
json_t *janus_admin_stream_summary(janus_ice_stream *stream) {
2249
        if(stream == NULL)
2250
                return NULL;
2251
        json_t *s = json_object();
2252
        json_object_set_new(s, "id", json_integer(stream->stream_id));
2253
        json_object_set_new(s, "ready", json_integer(stream->cdone));
2254
        json_object_set_new(s, "disabled", stream->disabled ? json_true() : json_false());
2255
        json_t *ss = json_object();
2256
        if(stream->audio_ssrc)
2257
                json_object_set_new(ss, "audio", json_integer(stream->audio_ssrc));
2258
        if(stream->video_ssrc)
2259
                json_object_set_new(ss, "video", json_integer(stream->video_ssrc));
2260
        if(stream->audio_ssrc_peer)
2261
                json_object_set_new(ss, "audio-peer", json_integer(stream->audio_ssrc_peer));
2262
        if(stream->video_ssrc_peer)
2263
                json_object_set_new(ss, "video-peer", json_integer(stream->video_ssrc_peer));
2264
        if(stream->video_ssrc_peer_rtx)
2265
                json_object_set_new(ss, "video-peer-rtx", json_integer(stream->video_ssrc_peer_rtx));
2266
        json_object_set_new(s, "ssrc", ss);
2267
        json_t *components = json_array();
2268
        if(stream->rtp_component) {
2269
                json_t *c = janus_admin_component_summary(stream->rtp_component);
2270
                if(c)
2271
                        json_array_append_new(components, c);
2272
        }
2273
        if(stream->rtcp_component) {
2274
                json_t *c = janus_admin_component_summary(stream->rtcp_component);
2275
                if(c)
2276
                        json_array_append_new(components, c);
2277
        }
2278
        json_t *rtcp_stats = NULL;
2279
        if(stream->audio_rtcp_ctx != NULL) {
2280
                rtcp_stats = json_object();
2281
                json_t *audio_rtcp_stats = json_object();
2282
                json_object_set_new(audio_rtcp_stats, "base", json_integer(stream->audio_rtcp_ctx->tb));
2283
                json_object_set_new(audio_rtcp_stats, "lsr", json_integer(janus_rtcp_context_get_lsr(stream->audio_rtcp_ctx)));
2284
                json_object_set_new(audio_rtcp_stats, "lost", json_integer(janus_rtcp_context_get_lost_all(stream->audio_rtcp_ctx, FALSE)));
2285
                json_object_set_new(audio_rtcp_stats, "lost-by-remote", json_integer(janus_rtcp_context_get_lost_all(stream->audio_rtcp_ctx, TRUE)));
2286
                json_object_set_new(audio_rtcp_stats, "jitter-local", json_integer(janus_rtcp_context_get_jitter(stream->audio_rtcp_ctx, FALSE)));
2287
                json_object_set_new(audio_rtcp_stats, "jitter-remote", json_integer(janus_rtcp_context_get_jitter(stream->audio_rtcp_ctx, TRUE)));
2288
                json_object_set_new(rtcp_stats, "audio", audio_rtcp_stats);
2289
        }
2290
        if(stream->video_rtcp_ctx != NULL) {
2291
                if(rtcp_stats == NULL)
2292
                        rtcp_stats = json_object();
2293
                json_t *video_rtcp_stats = json_object();
2294
                json_object_set_new(video_rtcp_stats, "base", json_integer(stream->video_rtcp_ctx->tb));
2295
                json_object_set_new(video_rtcp_stats, "lsr", json_integer(janus_rtcp_context_get_lsr(stream->video_rtcp_ctx)));
2296
                json_object_set_new(video_rtcp_stats, "lost", json_integer(janus_rtcp_context_get_lost_all(stream->video_rtcp_ctx, FALSE)));
2297
                json_object_set_new(video_rtcp_stats, "lost-by-remote", json_integer(janus_rtcp_context_get_lost_all(stream->video_rtcp_ctx, TRUE)));
2298
                json_object_set_new(video_rtcp_stats, "jitter-local", json_integer(janus_rtcp_context_get_jitter(stream->video_rtcp_ctx, FALSE)));
2299
                json_object_set_new(video_rtcp_stats, "jitter-remote", json_integer(janus_rtcp_context_get_jitter(stream->video_rtcp_ctx, TRUE)));
2300
                json_object_set_new(rtcp_stats, "video", video_rtcp_stats);
2301
        }
2302
        if(rtcp_stats != NULL)
2303
                json_object_set_new(s, "rtcp_stats", rtcp_stats);
2304
        json_object_set_new(s, "components", components);
2305
        return s;
2306
}
2307

    
2308
json_t *janus_admin_component_summary(janus_ice_component *component) {
2309
        if(component == NULL)
2310
                return NULL;
2311
        janus_ice_handle *handle = component->stream ? component->stream->handle : NULL;
2312
        json_t *c = json_object();
2313
        json_object_set_new(c, "id", json_integer(component->component_id));
2314
        json_object_set_new(c, "state", json_string(janus_get_ice_state_name(component->state)));
2315
        if(component->component_connected > 0)
2316
                json_object_set_new(c, "connected", json_integer(component->component_connected));
2317
        if(component->local_candidates) {
2318
                json_t *cs = json_array();
2319
                GSList *candidates = component->local_candidates, *i = NULL;
2320
                for (i = candidates; i; i = i->next) {
2321
                        gchar *lc = (gchar *) i->data;
2322
                        if(lc)
2323
                                json_array_append_new(cs, json_string(lc));
2324
                }
2325
                json_object_set_new(c, "local-candidates", cs);
2326
        }
2327
        if(component->remote_candidates) {
2328
                json_t *cs = json_array();
2329
                GSList *candidates = component->remote_candidates, *i = NULL;
2330
                for (i = candidates; i; i = i->next) {
2331
                        gchar *rc = (gchar *) i->data;
2332
                        if(rc)
2333
                                json_array_append_new(cs, json_string(rc));
2334
                }
2335
                json_object_set_new(c, "remote-candidates", cs);
2336
        }
2337
        if(component->selected_pair) {
2338
                json_object_set_new(c, "selected-pair", json_string(component->selected_pair));
2339
        }
2340
        json_t *d = json_object();
2341
        json_t *in_stats = json_object();
2342
        json_t *out_stats = json_object();
2343
        if(component->dtls) {
2344
                janus_dtls_srtp *dtls = component->dtls;
2345
                json_object_set_new(d, "fingerprint", json_string(janus_dtls_get_local_fingerprint()));
2346
                json_object_set_new(d, "remote-fingerprint", json_string(component->stream->remote_fingerprint));
2347
                json_object_set_new(d, "remote-fingerprint-hash", json_string(component->stream->remote_hashing));
2348
                json_object_set_new(d, "dtls-role", json_string(janus_get_dtls_srtp_role(component->stream->dtls_role)));
2349
                json_object_set_new(d, "dtls-state", json_string(janus_get_dtls_srtp_state(dtls->dtls_state)));
2350
                json_object_set_new(d, "valid", dtls->srtp_valid ? json_true() : json_false());
2351
                json_object_set_new(d, "ready", dtls->ready ? json_true() : json_false());
2352
                if(dtls->dtls_connected > 0)
2353
                        json_object_set_new(d, "connected", json_integer(dtls->dtls_connected));
2354
                if(handle && janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_AUDIO)) {
2355
                        json_object_set_new(in_stats, "audio_packets", json_integer(component->in_stats.audio_packets));
2356
                        json_object_set_new(in_stats, "audio_bytes", json_integer(component->in_stats.audio_bytes));
2357
                        json_object_set_new(in_stats, "audio_nacks", json_integer(component->in_stats.audio_nacks));
2358
                        /* Compute the last second stuff too */
2359
                        gint64 now = janus_get_monotonic_time();
2360
                        guint64 bytes = 0;
2361
                        if(component->in_stats.audio_bytes_lastsec) {
2362
                                GList *lastsec = component->in_stats.audio_bytes_lastsec;
2363
                                while(lastsec) {
2364
                                        janus_ice_stats_item *s = (janus_ice_stats_item *)lastsec->data;
2365
                                        if(s && now-s->when < G_USEC_PER_SEC)
2366
                                                bytes += s->bytes;
2367
                                        lastsec = lastsec->next;
2368
                                }
2369
                        }
2370
                        json_object_set_new(in_stats, "audio_bytes_lastsec", json_integer(bytes));
2371
                }
2372
                if(handle && janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_VIDEO)) {
2373
                        json_object_set_new(in_stats, "video_packets", json_integer(component->in_stats.video_packets));
2374
                        json_object_set_new(in_stats, "video_bytes", json_integer(component->in_stats.video_bytes));
2375
                        json_object_set_new(in_stats, "video_nacks", json_integer(component->in_stats.video_nacks));
2376
                        /* Compute the last second stuff too */
2377
                        gint64 now = janus_get_monotonic_time();
2378
                        guint64 bytes = 0;
2379
                        if(component->in_stats.video_bytes_lastsec) {
2380
                                GList *lastsec = component->in_stats.video_bytes_lastsec;
2381
                                while(lastsec) {
2382
                                        janus_ice_stats_item *s = (janus_ice_stats_item *)lastsec->data;
2383
                                        if(s && now-s->when < G_USEC_PER_SEC)
2384
                                                bytes += s->bytes;
2385
                                        lastsec = lastsec->next;
2386
                                }
2387
                        }
2388
                        json_object_set_new(in_stats, "video_bytes_lastsec", json_integer(bytes));
2389
                }
2390
                json_object_set_new(in_stats, "data_packets", json_integer(component->in_stats.data_packets));
2391
                json_object_set_new(in_stats, "data_bytes", json_integer(component->in_stats.data_bytes));
2392
                if(handle && janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_AUDIO)) {
2393
                        json_object_set_new(out_stats, "audio_packets", json_integer(component->out_stats.audio_packets));
2394
                        json_object_set_new(out_stats, "audio_bytes", json_integer(component->out_stats.audio_bytes));
2395
                        json_object_set_new(out_stats, "audio_nacks", json_integer(component->out_stats.audio_nacks));
2396
                }
2397
                if(handle && janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_HAS_VIDEO)) {
2398
                        json_object_set_new(out_stats, "video_packets", json_integer(component->out_stats.video_packets));
2399
                        json_object_set_new(out_stats, "video_bytes", json_integer(component->out_stats.video_bytes));
2400
                        json_object_set_new(out_stats, "video_nacks", json_integer(component->out_stats.video_nacks));
2401
                }
2402
                json_object_set_new(out_stats, "data_packets", json_integer(component->out_stats.data_packets));
2403
                json_object_set_new(out_stats, "data_bytes", json_integer(component->out_stats.data_bytes));
2404
#ifdef HAVE_SCTP
2405
                /* FIXME Actually check if this succeeded? */
2406
                json_object_set_new(d, "sctp-association", dtls->sctp ? json_true() : json_false());
2407
#endif
2408
        }
2409
        json_object_set_new(c, "dtls", d);
2410
        json_object_set_new(c, "in_stats", in_stats);
2411
        json_object_set_new(c, "out_stats", out_stats);
2412
        return c;
2413
}
2414

    
2415

    
2416
/* Transports */
2417
void janus_transport_close(gpointer key, gpointer value, gpointer user_data) {
2418
        janus_transport *transport = (janus_transport *)value;
2419
        if(!transport)
2420
                return;
2421
        transport->destroy();
2422
}
2423

    
2424
void janus_transportso_close(gpointer key, gpointer value, gpointer user_data) {
2425
        void *transport = value;
2426
        if(!transport)
2427
                return;
2428
        /* FIXME We don't dlclose transports to be sure we can detect leaks */
2429
        //~ dlclose(transport);
2430
}
2431

    
2432
/* Transport callback interface */
2433
void janus_transport_incoming_request(janus_transport *plugin, void *transport, void *request_id, gboolean admin, json_t *message, json_error_t *error) {
2434
        JANUS_LOG(LOG_VERB, "Got %s API request from %s (%p)\n", admin ? "an admin" : "a Janus", plugin->get_package(), transport);
2435
        /* Create a janus_request instance to handle the request */
2436
        janus_request *request = janus_request_new(plugin, transport, request_id, admin, message);
2437
        GError *tperror = NULL;
2438
        g_thread_pool_push(tasks, request, &tperror);
2439
        if(tperror != NULL) {
2440
                /* Something went wrong... */
2441
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to push task in thread pool...\n", tperror->code, tperror->message ? tperror->message : "??");
2442
                json_t *transaction = json_object_get(message, "transaction");
2443
                const char *transaction_text = json_is_string(transaction) ? json_string_value(transaction) : NULL;
2444
                janus_process_error(request, 0, transaction_text, JANUS_ERROR_UNKNOWN, "Thread pool error");
2445
                janus_request_destroy(request);
2446
        }
2447
}
2448

    
2449
void janus_transport_gone(janus_transport *plugin, void *transport) {
2450
        /* Get rid of sessions this transport was handling */
2451
        JANUS_LOG(LOG_VERB, "A %s transport instance has gone away (%p)\n", plugin->get_package(), transport);
2452
        janus_mutex_lock(&sessions_mutex);
2453
        if(sessions && g_hash_table_size(sessions) > 0) {
2454
                GHashTableIter iter;
2455
                gpointer value;
2456
                g_hash_table_iter_init(&iter, sessions);
2457
                while(g_hash_table_iter_next(&iter, NULL, &value)) {
2458
                        janus_session *session = (janus_session *) value;
2459
                        if(!session || session->destroy || session->timeout || session->last_activity == 0)
2460
                                continue;
2461
                        if(session->source && session->source->instance == transport) {
2462
                                JANUS_LOG(LOG_VERB, "  -- Marking Session %"SCNu64" as over\n", session->session_id);
2463
                                session->last_activity = 0;        /* This will trigger a timeout */
2464
                        }
2465
                }
2466
        }
2467
        janus_mutex_unlock(&sessions_mutex);
2468
}
2469

    
2470
gboolean janus_transport_is_api_secret_needed(janus_transport *plugin) {
2471
        return api_secret != NULL;
2472
}
2473

    
2474
gboolean janus_transport_is_api_secret_valid(janus_transport *plugin, const char *apisecret) {
2475
        if(api_secret == NULL)
2476
                return TRUE;
2477
        return apisecret && janus_strcmp_const_time(apisecret, api_secret);
2478
}
2479

    
2480
gboolean janus_transport_is_auth_token_needed(janus_transport *plugin) {
2481
        return janus_auth_is_enabled();
2482
}
2483

    
2484
gboolean janus_transport_is_auth_token_valid(janus_transport *plugin, const char *token) {
2485
        if(!janus_auth_is_enabled())
2486
                return TRUE;
2487
        return token && janus_auth_check_token(token);
2488
}
2489

    
2490
void janus_transport_notify_event(janus_transport *plugin, void *transport, json_t *event) {
2491
        /* A plugin asked to notify an event to the handlers */
2492
        if(!plugin || !event || !json_is_object(event))
2493
                return;
2494
        /* Notify event handlers */
2495
        if(janus_events_is_enabled()) {
2496
                janus_events_notify_handlers(JANUS_EVENT_TYPE_TRANSPORT,
2497
                        0, plugin->get_package(), transport, event);
2498
        } else {
2499
                json_decref(event);
2500
        }
2501
}
2502

    
2503
void janus_transport_task(gpointer data, gpointer user_data) {
2504
        JANUS_LOG(LOG_VERB, "Transport task pool, serving request\n");
2505
        janus_request *request = (janus_request *)data;
2506
        if(request == NULL) {
2507
                JANUS_LOG(LOG_ERR, "Missing request\n");
2508
                return;
2509
        }
2510
        if(!request->admin)
2511
                janus_process_incoming_request(request);
2512
        else
2513
                janus_process_incoming_admin_request(request);
2514
        /* Done */
2515
        janus_request_destroy(request);
2516
}
2517

    
2518

    
2519
/* Event handlers */
2520
void janus_eventhandler_close(gpointer key, gpointer value, gpointer user_data) {
2521
        janus_eventhandler *eventhandler = (janus_eventhandler *)value;
2522
        if(!eventhandler)
2523
                return;
2524
        eventhandler->destroy();
2525
}
2526

    
2527
void janus_eventhandlerso_close(gpointer key, gpointer value, gpointer user_data) {
2528
        void *eventhandler = (janus_eventhandler *)value;
2529
        if(!eventhandler)
2530
                return;
2531
        //~ dlclose(eventhandler);
2532
}
2533

    
2534

    
2535
/* Plugins */
2536
void janus_plugin_close(gpointer key, gpointer value, gpointer user_data) {
2537
        janus_plugin *plugin = (janus_plugin *)value;
2538
        if(!plugin)
2539
                return;
2540
        plugin->destroy();
2541
}
2542

    
2543
void janus_pluginso_close(gpointer key, gpointer value, gpointer user_data) {
2544
        void *plugin = value;
2545
        if(!plugin)
2546
                return;
2547
        /* FIXME We don't dlclose plugins to be sure we can detect leaks */
2548
        //~ dlclose(plugin);
2549
}
2550

    
2551
janus_plugin *janus_plugin_find(const gchar *package) {
2552
        if(package != NULL && plugins != NULL)        /* FIXME Do we need to fix the key pointer? */
2553
                return g_hash_table_lookup(plugins, package);
2554
        return NULL;
2555
}
2556

    
2557

    
2558
/* Plugin callback interface */
2559
int janus_plugin_push_event(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *transaction, json_t *message, json_t *jsep) {
2560
        if(!plugin || !message)
2561
                return -1;
2562
        if(!plugin_session || plugin_session < (janus_plugin_session *)0x1000 ||
2563
                        !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped)
2564
                return -2;
2565
        janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
2566
        if(!ice_handle || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP))
2567
                return JANUS_ERROR_SESSION_NOT_FOUND;
2568
        janus_session *session = ice_handle->session;
2569
        if(!session || session->destroy)
2570
                return JANUS_ERROR_SESSION_NOT_FOUND;
2571
        /* Make sure this is a JSON object */
2572
        if(!json_is_object(message)) {
2573
                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Cannot push event (JSON error: not an object)\n", ice_handle->handle_id);
2574
                return JANUS_ERROR_INVALID_JSON_OBJECT;
2575
        }
2576
        /* Attach JSEP if possible? */
2577
        const char *sdp_type = json_string_value(json_object_get(jsep, "type"));
2578
        const char *sdp = json_string_value(json_object_get(jsep, "sdp"));
2579
        json_t *merged_jsep = NULL;
2580
        if(sdp_type != NULL && sdp != NULL) {
2581
                merged_jsep = janus_plugin_handle_sdp(plugin_session, plugin, sdp_type, sdp);
2582
                if(merged_jsep == NULL) {
2583
                        if(ice_handle == NULL || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
2584
                                        || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT)) {
2585
                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Cannot push event (handle not available anymore or negotiation stopped)\n", ice_handle->handle_id);
2586
                                return JANUS_ERROR_HANDLE_NOT_FOUND;
2587
                        } else {
2588
                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Cannot push event (JSON error: problem with the SDP)\n", ice_handle->handle_id);
2589
                                return JANUS_ERROR_JSEP_INVALID_SDP;
2590
                        }
2591
                }
2592
        }
2593
        /* Reference the payload, as the plugin may still need it and will do a decref itself */
2594
        json_incref(message);
2595
        /* Prepare JSON event */
2596
        json_t *event = json_object();
2597
        json_object_set_new(event, "janus", json_string("event"));
2598
        json_object_set_new(event, "session_id", json_integer(session->session_id));
2599
        json_object_set_new(event, "sender", json_integer(ice_handle->handle_id));
2600
        if(transaction != NULL)
2601
                json_object_set_new(event, "transaction", json_string(transaction));
2602
        json_t *plugin_data = json_object();
2603
        json_object_set_new(plugin_data, "plugin", json_string(plugin->get_package()));
2604
        json_object_set_new(plugin_data, "data", message);
2605
        json_object_set_new(event, "plugindata", plugin_data);
2606
        if(merged_jsep != NULL)
2607
                json_object_set_new(event, "jsep", merged_jsep);
2608
        /* Send the event */
2609
        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Sending event to transport...\n", ice_handle->handle_id);
2610
        janus_session_notify_event(session->session_id, event);
2611

    
2612
        if(jsep != NULL && janus_events_is_enabled()) {
2613
                /* Notify event handlers as well */
2614
                janus_events_notify_handlers(JANUS_EVENT_TYPE_JSEP,
2615
                        session->session_id, ice_handle->handle_id, "local", sdp_type, sdp);
2616
        }
2617

    
2618
        return JANUS_OK;
2619
}
2620

    
2621
json_t *janus_plugin_handle_sdp(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *sdp_type, const char *sdp) {
2622
        if(!plugin_session || plugin_session < (janus_plugin_session *)0x1000 ||
2623
                        !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped ||
2624
                        plugin == NULL || sdp_type == NULL || sdp == NULL) {
2625
                JANUS_LOG(LOG_ERR, "Invalid arguments\n");
2626
                return NULL;
2627
        }
2628
        janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
2629
        //~ if(ice_handle == NULL || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_READY)) {
2630
        if(ice_handle == NULL) {
2631
                JANUS_LOG(LOG_ERR, "Invalid ICE handle\n");
2632
                return NULL;
2633
        }
2634
        int offer = 0;
2635
        if(!strcasecmp(sdp_type, "offer")) {
2636
                /* This is an offer from a plugin */
2637
                offer = 1;
2638
                janus_flags_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_OFFER);
2639
                janus_flags_clear(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_ANSWER);
2640
        } else if(!strcasecmp(sdp_type, "answer")) {
2641
                /* This is an answer from a plugin */
2642
                janus_flags_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_ANSWER);
2643
        } else {
2644
                /* TODO Handle other messages */
2645
                JANUS_LOG(LOG_ERR, "Unknown type '%s'\n", sdp_type);
2646
                return NULL;
2647
        }
2648
        /* Is this valid SDP? */
2649
        char error_str[512];
2650
        int audio = 0, video = 0, data = 0, bundle = 0, rtcpmux = 0, trickle = 0;
2651
        janus_sdp *parsed_sdp = janus_sdp_preparse(sdp, error_str, sizeof(error_str), &audio, &video, &data, &bundle, &rtcpmux, &trickle);
2652
        if(parsed_sdp == NULL) {
2653
                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Couldn't parse SDP... %s\n", ice_handle->handle_id, error_str);
2654
                return NULL;
2655
        }
2656
        gboolean updating = FALSE;
2657
        if(offer) {
2658
                /* We still don't have a local ICE setup */
2659
                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Audio %s been negotiated\n", ice_handle->handle_id, audio ? "has" : "has NOT");
2660
                if(audio > 1) {
2661
                        JANUS_LOG(LOG_ERR, "[%"SCNu64"] More than one audio line? only going to negotiate one...\n", ice_handle->handle_id);
2662
                }
2663
                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Video %s been negotiated\n", ice_handle->handle_id, video ? "has" : "has NOT");
2664
                if(video > 1) {
2665
                        JANUS_LOG(LOG_ERR, "[%"SCNu64"] More than one video line? only going to negotiate one...\n", ice_handle->handle_id);
2666
                }
2667
                JANUS_LOG(LOG_VERB, "[%"SCNu64"] SCTP/DataChannels %s been negotiated\n", ice_handle->handle_id, data ? "have" : "have NOT");
2668
                if(data > 1) {
2669
                        JANUS_LOG(LOG_ERR, "[%"SCNu64"] More than one data line? only going to negotiate one...\n", ice_handle->handle_id);
2670
                }
2671
#ifndef HAVE_SCTP
2672
                if(data) {
2673
                        JANUS_LOG(LOG_WARN, "[%"SCNu64"]   -- DataChannels have been negotiated, but support for them has not been compiled...\n", ice_handle->handle_id);
2674
                }
2675
#endif
2676
                /* Are we still cleaning up from a previous media session? */
2677
                if(janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_CLEANING)) {
2678
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Still cleaning up from a previous media session, let's wait a bit...\n", ice_handle->handle_id);
2679
                        gint64 waited = 0;
2680
                        while(janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_CLEANING)) {
2681
                                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Still cleaning up from a previous media session, let's wait a bit...\n", ice_handle->handle_id);
2682
                                g_usleep(100000);
2683
                                waited += 100000;
2684
                                if(waited >= 3*G_USEC_PER_SEC) {
2685
                                        JANUS_LOG(LOG_VERB, "[%"SCNu64"]   -- Waited 3 seconds, that's enough!\n", ice_handle->handle_id);
2686
                                        break;
2687
                                }
2688
                        }
2689
                }
2690
                if(ice_handle->agent == NULL) {
2691
                        /* Process SDP in order to setup ICE locally (this is going to result in an answer from the browser) */
2692
                        if(janus_ice_setup_local(ice_handle, 0, audio, video, data, bundle, rtcpmux, trickle) < 0) {
2693
                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Error setting ICE locally\n", ice_handle->handle_id);
2694
                                janus_sdp_free(parsed_sdp);
2695
                                return NULL;
2696
                        }
2697
                } else {
2698
                        updating = TRUE;
2699
                        JANUS_LOG(LOG_INFO, "[%"SCNu64"] Updating existing session\n", ice_handle->handle_id);
2700
                }
2701
        }
2702
        if(!updating) {
2703
                /* Wait for candidates-done callback */
2704
                while(ice_handle->cdone < ice_handle->streams_num) {
2705
                        if(ice_handle == NULL || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
2706
                                        || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT)) {
2707
                                JANUS_LOG(LOG_WARN, "[%"SCNu64"] Handle detached or PC closed, giving up...!\n", ice_handle ? ice_handle->handle_id : 0);
2708
                                janus_sdp_free(parsed_sdp);
2709
                                return NULL;
2710
                        }
2711
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Waiting for candidates-done callback...\n", ice_handle->handle_id);
2712
                        g_usleep(100000);
2713
                        if(ice_handle->cdone < 0) {
2714
                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Error gathering candidates!\n", ice_handle->handle_id);
2715
                                janus_sdp_free(parsed_sdp);
2716
                                return NULL;
2717
                        }
2718
                }
2719
        }
2720
        /* Anonymize SDP */
2721
        if(janus_sdp_anonymize(parsed_sdp) < 0) {
2722
                /* Invalid SDP */
2723
                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Invalid SDP\n", ice_handle->handle_id);
2724
                janus_sdp_free(parsed_sdp);
2725
                return NULL;
2726
        }
2727
        /* Add our details */
2728
        char *sdp_merged = janus_sdp_merge(ice_handle, parsed_sdp);
2729
        if(sdp_merged == NULL) {
2730
                /* Couldn't merge SDP */
2731
                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Error merging SDP\n", ice_handle->handle_id);
2732
                janus_sdp_free(parsed_sdp);
2733
                return NULL;
2734
        }
2735
        janus_sdp_free(parsed_sdp);
2736
        /* FIXME Any disabled m-line? */
2737
        if(strstr(sdp_merged, "m=audio 0")) {
2738
                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Audio disabled via SDP\n", ice_handle->handle_id);
2739
                if(!janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)
2740
                                || (!video && !data)) {
2741
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"]   -- Marking audio stream as disabled\n", ice_handle->handle_id);
2742
                        janus_ice_stream *stream = g_hash_table_lookup(ice_handle->streams, GUINT_TO_POINTER(ice_handle->audio_id));
2743
                        if(stream)
2744
                                stream->disabled = TRUE;
2745
                }
2746
        }
2747
        if(strstr(sdp_merged, "m=video 0")) {
2748
                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Video disabled via SDP\n", ice_handle->handle_id);
2749
                if(!janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)
2750
                                || (!audio && !data)) {
2751
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"]   -- Marking video stream as disabled\n", ice_handle->handle_id);
2752
                        janus_ice_stream *stream = NULL;
2753
                        if(!janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)) {
2754
                                stream = g_hash_table_lookup(ice_handle->streams, GUINT_TO_POINTER(ice_handle->video_id));
2755
                        } else {
2756
                                gint id = ice_handle->audio_id > 0 ? ice_handle->audio_id : ice_handle->video_id;
2757
                                stream = g_hash_table_lookup(ice_handle->streams, GUINT_TO_POINTER(id));
2758
                        }
2759
                        if(stream)
2760
                                stream->disabled = TRUE;
2761
                }
2762
        }
2763
        if(strstr(sdp_merged, "m=application 0 DTLS/SCTP")) {
2764
                JANUS_LOG(LOG_VERB, "[%"SCNu64"] Data Channel disabled via SDP\n", ice_handle->handle_id);
2765
                if(!janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)
2766
                                || (!audio && !video)) {
2767
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"]   -- Marking data channel stream as disabled\n", ice_handle->handle_id);
2768
                        janus_ice_stream *stream = NULL;
2769
                        if(!janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_BUNDLE)) {
2770
                                stream = g_hash_table_lookup(ice_handle->streams, GUINT_TO_POINTER(ice_handle->data_id));
2771
                        } else {
2772
                                gint id = ice_handle->audio_id > 0 ? ice_handle->audio_id : (ice_handle->video_id > 0 ? ice_handle->video_id : ice_handle->data_id);
2773
                                stream = g_hash_table_lookup(ice_handle->streams, GUINT_TO_POINTER(id));
2774
                        }
2775
                        if(stream)
2776
                                stream->disabled = TRUE;
2777
                }
2778
        }
2779

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

    
2949
        /* Prepare JSON event */
2950
        json_t *jsep = json_object();
2951
        json_object_set_new(jsep, "type", json_string(sdp_type));
2952
        json_object_set_new(jsep, "sdp", json_string(sdp_merged));
2953
        ice_handle->local_sdp = sdp_merged;
2954
        return jsep;
2955
}
2956

    
2957
void janus_plugin_relay_rtp(janus_plugin_session *plugin_session, int video, char *buf, int len) {
2958
        if((plugin_session < (janus_plugin_session *)0x1000) || plugin_session->stopped || buf == NULL || len < 1)
2959
                return;
2960
        janus_ice_handle *handle = (janus_ice_handle *)plugin_session->gateway_handle;
2961
        if(!handle || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
2962
                        || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
2963
                return;
2964
        janus_ice_relay_rtp(handle, video, buf, len);
2965
}
2966

    
2967
void janus_plugin_relay_rtcp(janus_plugin_session *plugin_session, int video, char *buf, int len) {
2968
        if((plugin_session < (janus_plugin_session *)0x1000) || plugin_session->stopped || buf == NULL || len < 1)
2969
                return;
2970
        janus_ice_handle *handle = (janus_ice_handle *)plugin_session->gateway_handle;
2971
        if(!handle || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
2972
                        || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
2973
                return;
2974
        janus_ice_relay_rtcp(handle, video, buf, len);
2975
}
2976

    
2977
void janus_plugin_relay_data(janus_plugin_session *plugin_session, char *buf, int len) {
2978
        if((plugin_session < (janus_plugin_session *)0x1000) || plugin_session->stopped || buf == NULL || len < 1)
2979
                return;
2980
        janus_ice_handle *handle = (janus_ice_handle *)plugin_session->gateway_handle;
2981
        if(!handle || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
2982
                        || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
2983
                return;
2984
#ifdef HAVE_SCTP
2985
        janus_ice_relay_data(handle, buf, len);
2986
#else
2987
        JANUS_LOG(LOG_WARN, "Asked to relay data, but Data Channels support has not been compiled...\n");
2988
#endif
2989
}
2990

    
2991
void janus_plugin_close_pc(janus_plugin_session *plugin_session) {
2992
        /* A plugin asked to get rid of a PeerConnection */
2993
        if((plugin_session < (janus_plugin_session *)0x1000) || !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped)
2994
                return;
2995
        janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
2996
        if(!ice_handle)
2997
                return;
2998
        if(janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
2999
                        || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
3000
                return;
3001
        janus_session *session = (janus_session *)ice_handle->session;
3002
        if(!session)
3003
                return;
3004

    
3005
        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Plugin asked to hangup PeerConnection: sending alert\n", ice_handle->handle_id);
3006
        /* Send an alert on all the DTLS connections */
3007
        janus_ice_webrtc_hangup(ice_handle);
3008
}
3009

    
3010
void janus_plugin_end_session(janus_plugin_session *plugin_session) {
3011
        /* A plugin asked to get rid of a handle */
3012
        if((plugin_session < (janus_plugin_session *)0x1000) || !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped)
3013
                return;
3014
        janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
3015
        if(!ice_handle)
3016
                return;
3017
        janus_session *session = (janus_session *)ice_handle->session;
3018
        if(!session)
3019
                return;
3020
        /* Destroy the handle */
3021
        janus_ice_handle_destroy(session, ice_handle->handle_id);
3022
        janus_mutex_lock(&session->mutex);
3023
        g_hash_table_remove(session->ice_handles, &ice_handle->handle_id);
3024
        janus_mutex_unlock(&session->mutex);
3025
}
3026

    
3027
void janus_plugin_notify_event(janus_plugin *plugin, janus_plugin_session *plugin_session, json_t *event) {
3028
        /* A plugin asked to notify an event to the handlers */
3029
        if(!plugin || !event || !json_is_object(event))
3030
                return;
3031
        guint64 session_id = 0, handle_id = 0;
3032
        if(plugin_session != NULL) {
3033
                if((plugin_session < (janus_plugin_session *)0x1000) || !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped) {
3034
                        json_decref(event);
3035
                        return;
3036
                }
3037
                janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
3038
                if(!ice_handle) {
3039
                        json_decref(event);
3040
                        return;
3041
                }
3042
                handle_id = ice_handle->handle_id;
3043
                janus_session *session = (janus_session *)ice_handle->session;
3044
                if(!session) {
3045
                        json_decref(event);
3046
                        return;
3047
                }
3048
                session_id = session->session_id;
3049
        }
3050
        /* Notify event handlers */
3051
        if(janus_events_is_enabled()) {
3052
                janus_events_notify_handlers(JANUS_EVENT_TYPE_PLUGIN,
3053
                        session_id, handle_id, plugin->get_package(), event);
3054
        } else {
3055
                json_decref(event);
3056
        }
3057
}
3058

    
3059

    
3060
static void janus_detect_local_ip(gchar *buf, size_t buflen) {
3061
        JANUS_LOG(LOG_VERB, "Autodetecting local IP...\n");
3062
        struct sockaddr_in addr;
3063
        socklen_t len;
3064
        int fd = socket(AF_INET, SOCK_DGRAM, 0);
3065
        if (fd == -1)
3066
                goto error;
3067
        addr.sin_family = AF_INET;
3068
        addr.sin_port = htons(1);
3069
        inet_pton(AF_INET, "1.2.3.4", &addr.sin_addr.s_addr);
3070
        if (connect(fd, (const struct sockaddr*) &addr, sizeof(addr)) < 0)
3071
                goto error;
3072
        len = sizeof(addr);
3073
        if (getsockname(fd, (struct sockaddr*) &addr, &len) < 0)
3074
                goto error;
3075
        if (getnameinfo((const struct sockaddr*) &addr, sizeof(addr),
3076
                        buf, buflen,
3077
                        NULL, 0, NI_NUMERICHOST) != 0)
3078
                goto error;
3079
        close(fd);
3080
        return;
3081
error:
3082
        if (fd != -1)
3083
                close(fd);
3084
        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");
3085
        g_strlcpy(buf, "127.0.0.1", buflen);
3086
}
3087

    
3088

    
3089
/* Main */
3090
gint main(int argc, char *argv[])
3091
{
3092
        /* Core dumps may be disallowed by parent of this process; change that */
3093
        struct rlimit core_limits;
3094
        core_limits.rlim_cur = core_limits.rlim_max = RLIM_INFINITY;
3095
        setrlimit(RLIMIT_CORE, &core_limits);
3096

    
3097
        struct gengetopt_args_info args_info;
3098
        /* Let's call our cmdline parser */
3099
        if(cmdline_parser(argc, argv, &args_info) != 0)
3100
                exit(1);
3101

    
3102
        /* Any configuration to open? */
3103
        if(args_info.config_given) {
3104
                config_file = g_strdup(args_info.config_arg);
3105
        }
3106
        if(args_info.configs_folder_given) {
3107
                configs_folder = g_strdup(args_info.configs_folder_arg);
3108
        } else {
3109
                configs_folder = g_strdup (CONFDIR);
3110
        }
3111
        if(config_file == NULL) {
3112
                char file[255];
3113
                g_snprintf(file, 255, "%s/janus.cfg", configs_folder);
3114
                config_file = g_strdup(file);
3115
        }
3116
        if((config = janus_config_parse(config_file)) == NULL) {
3117
                if(args_info.config_given) {
3118
                        /* We only give up if the configuration file was explicitly provided */
3119
                        g_print("Error reading configuration from %s\n", config_file);
3120
                        exit(1);
3121
                }
3122
                g_print("Error reading/parsing the configuration file, going on with the defaults and the command line arguments\n");
3123
                config = janus_config_create("janus.cfg");
3124
                if(config == NULL) {
3125
                        /* If we can't even create an empty configuration, something's definitely wrong */
3126
                        exit(1);
3127
                }
3128
        }
3129

    
3130
        /* Check if we need to log to console and/or file */
3131
        gboolean use_stdout = TRUE;
3132
        if(args_info.disable_stdout_given) {
3133
                use_stdout = FALSE;
3134
                janus_config_add_item(config, "general", "log_to_stdout", "no");
3135
        } else {
3136
                /* Check if the configuration file is saying anything about this */
3137
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "log_to_stdout");
3138
                if(item && item->value && !janus_is_true(item->value))
3139
                        use_stdout = FALSE;
3140
        }
3141
        const char *logfile = NULL;
3142
        if(args_info.log_file_given) {
3143
                logfile = args_info.log_file_arg;
3144
                janus_config_add_item(config, "general", "log_to_file", "no");
3145
        } else {
3146
                /* Check if the configuration file is saying anything about this */
3147
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "log_to_file");
3148
                if(item && item->value)
3149
                        logfile = item->value;
3150
        }
3151

    
3152
        /* Check if we're going to daemonize Janus */
3153
        if(args_info.daemon_given) {
3154
                daemonize = TRUE;
3155
                janus_config_add_item(config, "general", "daemonize", "yes");
3156
        } else {
3157
                /* Check if the configuration file is saying anything about this */
3158
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "daemonize");
3159
                if(item && item->value && janus_is_true(item->value))
3160
                        daemonize = TRUE;
3161
        }
3162
        /* If we're going to daemonize, make sure logging to stdout is disabled and a log file has been specified */
3163
        if(daemonize && use_stdout) {
3164
                use_stdout = FALSE;
3165
        }
3166
        if(daemonize && logfile == NULL) {
3167
                g_print("Running Janus as a daemon but no log file provided, giving up...\n");
3168
                exit(1);
3169
        }
3170
        /* Daemonize now, if we need to */
3171
        if(daemonize) {
3172
                g_print("Running Janus as a daemon\n");
3173

    
3174
                /* Create a pipe for parent<->child communication during the startup phase */
3175
                if(pipe(pipefd) == -1) {
3176
                        g_print("pipe error!\n");
3177
                        exit(1);
3178
                }
3179

    
3180
                /* Fork off the parent process */
3181
                pid_t pid = fork();
3182
                if(pid < 0) {
3183
                        g_print("Fork error!\n");
3184
                        exit(1);
3185
                }
3186
                if(pid > 0) {
3187
                        /* Ok, we're the parent: let's wait for the child to tell us everything started fine */
3188
                        close(pipefd[1]);
3189
                        int code = -1;
3190
                        struct pollfd pollfds;
3191

    
3192
                        while(code < 0) {
3193
                                pollfds.fd = pipefd[0];
3194
                                pollfds.events = POLLIN;
3195
                                int res = poll(&pollfds, 1, -1);
3196
                                if(res < 0)
3197
                                        break;
3198
                                if(res == 0)
3199
                                        continue;
3200
                                if(pollfds.revents & POLLERR || pollfds.revents & POLLHUP)
3201
                                        break;
3202
                                if(pollfds.revents & POLLIN) {
3203
                                        res = read(pipefd[0], &code, sizeof(int));
3204
                                        break;
3205
                                }
3206
                        }
3207
                        if(code < 0)
3208
                                code = 1;
3209

    
3210
                        /* Leave the parent and return the exit code we received from the child */
3211
                        if(code)
3212
                                g_print("Error launching Janus (error code %d), check the logs for more details\n", code);
3213
                        exit(code);
3214
                }
3215
                /* Change the file mode mask */
3216
                umask(0);
3217

    
3218
                /* Create a new SID for the child process */
3219
                pid_t sid = setsid();
3220
                if(sid < 0) {
3221
                        g_print("Error setting SID!\n");
3222
                        exit(1);
3223
                }
3224
                /* Change the current working directory */
3225
                if((chdir("/")) < 0) {
3226
                        g_print("Error changing the current working directory!\n");
3227
                        exit(1);
3228
                }
3229
                /* We close stdin/stdout/stderr when initializing the logger */
3230
        }
3231

    
3232
        /* Initialize logger */
3233
        if(janus_log_init(daemonize, use_stdout, logfile) < 0)
3234
                exit(1);
3235

    
3236
        JANUS_PRINT("---------------------------------------------------\n");
3237
        JANUS_PRINT("  Starting Meetecho Janus (WebRTC Gateway) v%s\n", JANUS_VERSION_STRING);
3238
        JANUS_PRINT("---------------------------------------------------\n\n");
3239

    
3240
        /* Handle SIGINT (CTRL-C), SIGTERM (from service managers) */
3241
        signal(SIGINT, janus_handle_signal);
3242
        signal(SIGTERM, janus_handle_signal);
3243
        atexit(janus_termination_handler);
3244

    
3245
        /* Setup Glib */
3246
#if !GLIB_CHECK_VERSION(2, 36, 0)
3247
        g_type_init();
3248
#endif
3249

    
3250
        /* Logging level: default is info and no timestamps */
3251
        janus_log_level = LOG_INFO;
3252
        janus_log_timestamps = FALSE;
3253
        janus_log_colors = TRUE;
3254
        if(args_info.debug_level_given) {
3255
                if(args_info.debug_level_arg < LOG_NONE)
3256
                        args_info.debug_level_arg = 0;
3257
                else if(args_info.debug_level_arg > LOG_MAX)
3258
                        args_info.debug_level_arg = LOG_MAX;
3259
                janus_log_level = args_info.debug_level_arg;
3260
        }
3261

    
3262
        /* Any PID we need to create? */
3263
        const char *pidfile = NULL;
3264
        if(args_info.pid_file_given) {
3265
                pidfile = args_info.pid_file_arg;
3266
                janus_config_add_item(config, "general", "pid_file", pidfile);
3267
        } else {
3268
                /* Check if the configuration file is saying anything about this */
3269
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "pid_file");
3270
                if(item && item->value)
3271
                        pidfile = item->value;
3272
        }
3273
        if(janus_pidfile_create(pidfile) < 0)
3274
                exit(1);
3275

    
3276
        /* Proceed with the rest of the configuration */
3277
        janus_config_print(config);
3278
        if(args_info.debug_level_given) {
3279
                char debug[5];
3280
                g_snprintf(debug, 5, "%d", args_info.debug_level_arg);
3281
                janus_config_add_item(config, "general", "debug_level", debug);
3282
        } else {
3283
                /* No command line directive on logging, try the configuration file */
3284
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "debug_level");
3285
                if(item && item->value) {
3286
                        int temp_level = atoi(item->value);
3287
                        if(temp_level == 0 && strcmp(item->value, "0")) {
3288
                                JANUS_PRINT("Invalid debug level %s (configuration), using default (info=4)\n", item->value);
3289
                        } else {
3290
                                janus_log_level = temp_level;
3291
                                if(janus_log_level < LOG_NONE)
3292
                                        janus_log_level = 0;
3293
                                else if(janus_log_level > LOG_MAX)
3294
                                        janus_log_level = LOG_MAX;
3295
                        }
3296
                }
3297
        }
3298
        /* Any command line argument that should overwrite the configuration? */
3299
        JANUS_PRINT("Checking command line arguments...\n");
3300
        if(args_info.debug_timestamps_given) {
3301
                janus_config_add_item(config, "general", "debug_timestamps", "yes");
3302
        }
3303
        if(args_info.disable_colors_given) {
3304
                janus_config_add_item(config, "general", "debug_colors", "no");
3305
        }
3306
        if(args_info.server_name_given) {
3307
                janus_config_add_item(config, "general", "server_name", args_info.server_name_arg);
3308
        }
3309
         if(args_info.interface_given) {
3310
                janus_config_add_item(config, "general", "interface", args_info.interface_arg);
3311
        }
3312
        if(args_info.configs_folder_given) {
3313
                janus_config_add_item(config, "general", "configs_folder", args_info.configs_folder_arg);
3314
        }
3315
        if(args_info.plugins_folder_given) {
3316
                janus_config_add_item(config, "general", "plugins_folder", args_info.plugins_folder_arg);
3317
        }
3318
        if(args_info.apisecret_given) {
3319
                janus_config_add_item(config, "general", "api_secret", args_info.apisecret_arg);
3320
        }
3321
        if(args_info.token_auth_given) {
3322
                janus_config_add_item(config, "general", "token_auth", "yes");
3323
        }
3324
        if(args_info.cert_pem_given) {
3325
                janus_config_add_item(config, "certificates", "cert_pem", args_info.cert_pem_arg);
3326
        }
3327
        if(args_info.cert_key_given) {
3328
                janus_config_add_item(config, "certificates", "cert_key", args_info.cert_key_arg);
3329
        }
3330
        if(args_info.stun_server_given) {
3331
                /* Split in server and port (if port missing, use 3478 as default) */
3332
                char *stunport = strrchr(args_info.stun_server_arg, ':');
3333
                if(stunport != NULL) {
3334
                        *stunport = '\0';
3335
                        stunport++;
3336
                        janus_config_add_item(config, "nat", "stun_server", args_info.stun_server_arg);
3337
                        janus_config_add_item(config, "nat", "stun_port", stunport);
3338
                } else {
3339
                        janus_config_add_item(config, "nat", "stun_server", args_info.stun_server_arg);
3340
                        janus_config_add_item(config, "nat", "stun_port", "3478");
3341
                }
3342
        }
3343
        if(args_info.nat_1_1_given) {
3344
                janus_config_add_item(config, "nat", "nat_1_1_mapping", args_info.nat_1_1_arg);
3345
        }
3346
        if(args_info.ice_enforce_list_given) {
3347
                janus_config_add_item(config, "nat", "ice_enforce_list", args_info.ice_enforce_list_arg);
3348
        }
3349
        if(args_info.ice_ignore_list_given) {
3350
                janus_config_add_item(config, "nat", "ice_ignore_list", args_info.ice_ignore_list_arg);
3351
        }
3352
        if(args_info.libnice_debug_given) {
3353
                janus_config_add_item(config, "nat", "nice_debug", "true");
3354
        }
3355
        if(args_info.ice_lite_given) {
3356
                janus_config_add_item(config, "nat", "ice_lite", "true");
3357
        }
3358
        if(args_info.ice_tcp_given) {
3359
                janus_config_add_item(config, "nat", "ice_tcp", "true");
3360
        }
3361
        if(args_info.ipv6_candidates_given) {
3362
                janus_config_add_item(config, "media", "ipv6", "true");
3363
        }
3364
        if(args_info.force_bundle_given) {
3365
                janus_config_add_item(config, "media", "force-bundle", "true");
3366
        }
3367
        if(args_info.force_rtcp_mux_given) {
3368
                janus_config_add_item(config, "media", "force-rtcp-mux", "true");
3369
        }
3370
        if(args_info.max_nack_queue_given) {
3371
                char mnq[20];
3372
                g_snprintf(mnq, 20, "%d", args_info.max_nack_queue_arg);
3373
                janus_config_add_item(config, "media", "max_nack_queue", mnq);
3374
        }
3375
        if(args_info.rtp_port_range_given) {
3376
                janus_config_add_item(config, "media", "rtp_port_range", args_info.rtp_port_range_arg);
3377
        }
3378
        if(args_info.event_handlers_given) {
3379
                janus_config_add_item(config, "events", "broadcast", "yes");
3380
        }
3381
        janus_config_print(config);
3382

    
3383
        /* Logging/debugging */
3384
        JANUS_PRINT("Debug/log level is %d\n", janus_log_level);
3385
        janus_config_item *item = janus_config_get_item_drilldown(config, "general", "debug_timestamps");
3386
        if(item && item->value)
3387
                janus_log_timestamps = janus_is_true(item->value);
3388
        JANUS_PRINT("Debug/log timestamps are %s\n", janus_log_timestamps ? "enabled" : "disabled");
3389
        item = janus_config_get_item_drilldown(config, "general", "debug_colors");
3390
        if(item && item->value)
3391
                janus_log_colors = janus_is_true(item->value);
3392
        JANUS_PRINT("Debug/log colors are %s\n", janus_log_colors ? "enabled" : "disabled");
3393

    
3394
        /* Any IP/interface to enforce/ignore? */
3395
        item = janus_config_get_item_drilldown(config, "nat", "ice_enforce_list");
3396
        if(item && item->value) {
3397
                gchar **list = g_strsplit(item->value, ",", -1);
3398
                gchar *index = list[0];
3399
                if(index != NULL) {
3400
                        int i=0;
3401
                        while(index != NULL) {
3402
                                if(strlen(index) > 0) {
3403
                                        JANUS_LOG(LOG_INFO, "Adding '%s' to the ICE enforce list...\n", index);
3404
                                        janus_ice_enforce_interface(g_strdup(index));
3405
                                }
3406
                                i++;
3407
                                index = list[i];
3408
                        }
3409
                }
3410
                g_clear_pointer(&list, g_strfreev);
3411
        }
3412
        item = janus_config_get_item_drilldown(config, "nat", "ice_ignore_list");
3413
        if(item && item->value) {
3414
                gchar **list = g_strsplit(item->value, ",", -1);
3415
                gchar *index = list[0];
3416
                if(index != NULL) {
3417
                        int i=0;
3418
                        while(index != NULL) {
3419
                                if(strlen(index) > 0) {
3420
                                        JANUS_LOG(LOG_INFO, "Adding '%s' to the ICE ignore list...\n", index);
3421
                                        janus_ice_ignore_interface(g_strdup(index));
3422
                                }
3423
                                i++;
3424
                                index = list[i];
3425
                        }
3426
                }
3427
                g_clear_pointer(&list, g_strfreev);
3428
        }
3429
        /* What is the local IP? */
3430
        JANUS_LOG(LOG_VERB, "Selecting local IP address...\n");
3431
        gboolean local_ip_set = FALSE;
3432
        item = janus_config_get_item_drilldown(config, "general", "interface");
3433
        if(item && item->value) {
3434
                JANUS_LOG(LOG_VERB, "  -- Will try to use %s\n", item->value);
3435
                int family;
3436
                if (!janus_is_ip_valid(item->value, &family)) {
3437
                        JANUS_LOG(LOG_WARN, "Invalid local IP specified: %s, guessing the default...\n", item->value);
3438
                } else {
3439
                        /* Verify that we can actually bind to that address */
3440
                        int fd = socket(family, SOCK_DGRAM, 0);
3441
                        if (fd == -1) {
3442
                                JANUS_LOG(LOG_WARN, "Error creating test socket, falling back to detecting IP address...\n");
3443
                        } else {
3444
                                int r;
3445
                                struct sockaddr_storage ss;
3446
                                socklen_t addrlen;
3447
                                memset(&ss, 0, sizeof(ss));
3448
                                if (family == AF_INET) {
3449
                                        struct sockaddr_in *addr4 = (struct sockaddr_in*)&ss;
3450
                                        addr4->sin_family = AF_INET;
3451
                                        addr4->sin_port = 0;
3452
                                        inet_pton(AF_INET, item->value, &(addr4->sin_addr.s_addr));
3453
                                        addrlen = sizeof(struct sockaddr_in);
3454
                                } else {
3455
                                        struct sockaddr_in6 *addr6 = (struct sockaddr_in6*)&ss;
3456
                                        addr6->sin6_family = AF_INET6;
3457
                                        addr6->sin6_port = 0;
3458
                                        inet_pton(AF_INET6, item->value, &(addr6->sin6_addr.s6_addr));
3459
                                        addrlen = sizeof(struct sockaddr_in6);
3460
                                }
3461
                                r = bind(fd, (const struct sockaddr*)&ss, addrlen);
3462
                                close(fd);
3463
                                if (r < 0) {
3464
                                        JANUS_LOG(LOG_WARN, "Error setting local IP address to %s, falling back to detecting IP address...\n", item->value);
3465
                                } else {
3466
                                        g_strlcpy(local_ip, item->value, sizeof(local_ip));
3467
                                        local_ip_set = TRUE;
3468
                                }
3469
                        }
3470
                }
3471
        }
3472
        if (!local_ip_set)
3473
                janus_detect_local_ip(local_ip, sizeof(local_ip));
3474
        JANUS_LOG(LOG_INFO, "Using %s as local IP...\n", local_ip);
3475

    
3476
        /* Was a custom instance name provided? */
3477
        item = janus_config_get_item_drilldown(config, "general", "server_name");
3478
        if(item && item->value) {
3479
                server_name = g_strdup(item->value);
3480
        }
3481

    
3482
        /* Is there any API secret to consider? */
3483
        api_secret = NULL;
3484
        item = janus_config_get_item_drilldown(config, "general", "api_secret");
3485
        if(item && item->value) {
3486
                api_secret = g_strdup(item->value);
3487
        }
3488
        /* Is there any API secret to consider? */
3489
        admin_api_secret = NULL;
3490
        item = janus_config_get_item_drilldown(config, "general", "admin_secret");
3491
        if(item && item->value) {
3492
                admin_api_secret = g_strdup(item->value);
3493
        }
3494
        /* Also check if the token based authentication mechanism needs to be enabled */
3495
        item = janus_config_get_item_drilldown(config, "general", "token_auth");
3496
        janus_auth_init(item && item->value && janus_is_true(item->value));
3497

    
3498
        /* Initialize the recorder code */
3499
        item = janus_config_get_item_drilldown(config, "general", "recordings_tmp_ext");
3500
        if(item && item->value) {
3501
                janus_recorder_init(TRUE, item->value);
3502
        } else {
3503
                janus_recorder_init(FALSE, NULL);
3504
        }
3505

    
3506
        /* Setup ICE stuff (e.g., checking if the provided STUN server is correct) */
3507
        char *stun_server = NULL, *turn_server = NULL;
3508
        uint16_t stun_port = 0, turn_port = 0;
3509
        char *turn_type = NULL, *turn_user = NULL, *turn_pwd = NULL;
3510
        char *turn_rest_api = NULL, *turn_rest_api_key = NULL;
3511
#ifdef HAVE_LIBCURL
3512
        char *turn_rest_api_method = NULL;
3513
#endif
3514
        const char *nat_1_1_mapping = NULL;
3515
        uint16_t rtp_min_port = 0, rtp_max_port = 0;
3516
        gboolean ice_lite = FALSE, ice_tcp = FALSE, ipv6 = FALSE;
3517
        item = janus_config_get_item_drilldown(config, "media", "ipv6");
3518
        ipv6 = (item && item->value) ? janus_is_true(item->value) : FALSE;
3519
        item = janus_config_get_item_drilldown(config, "media", "rtp_port_range");
3520
        if(item && item->value) {
3521
                /* Split in min and max port */
3522
                char *maxport = strrchr(item->value, '-');
3523
                if(maxport != NULL) {
3524
                        *maxport = '\0';
3525
                        maxport++;
3526
                        rtp_min_port = atoi(item->value);
3527
                        rtp_max_port = atoi(maxport);
3528
                        maxport--;
3529
                        *maxport = '-';
3530
                }
3531
                if(rtp_min_port > rtp_max_port) {
3532
                        int temp_port = rtp_min_port;
3533
                        rtp_min_port = rtp_max_port;
3534
                        rtp_max_port = temp_port;
3535
                }
3536
                if(rtp_max_port == 0)
3537
                        rtp_max_port = 65535;
3538
                JANUS_LOG(LOG_INFO, "RTP port range: %u -- %u\n", rtp_min_port, rtp_max_port);
3539
        }
3540
        /* Check if we need to enable the ICE Lite mode */
3541
        item = janus_config_get_item_drilldown(config, "nat", "ice_lite");
3542
        ice_lite = (item && item->value) ? janus_is_true(item->value) : FALSE;
3543
        /* Check if we need to enable ICE-TCP support (warning: still broken, for debugging only) */
3544
        item = janus_config_get_item_drilldown(config, "nat", "ice_tcp");
3545
        ice_tcp = (item && item->value) ? janus_is_true(item->value) : FALSE;
3546
        /* Any STUN server to use in Janus? */
3547
        item = janus_config_get_item_drilldown(config, "nat", "stun_server");
3548
        if(item && item->value)
3549
                stun_server = (char *)item->value;
3550
        item = janus_config_get_item_drilldown(config, "nat", "stun_port");
3551
        if(item && item->value)
3552
                stun_port = atoi(item->value);
3553
        /* Any 1:1 NAT mapping to take into account? */
3554
        item = janus_config_get_item_drilldown(config, "nat", "nat_1_1_mapping");
3555
        if(item && item->value) {
3556
                JANUS_LOG(LOG_VERB, "Using nat_1_1_mapping for public ip - %s\n", item->value);
3557
                nat_1_1_mapping = item->value;
3558
                janus_set_public_ip(item->value);
3559
                janus_ice_enable_nat_1_1();
3560
        }
3561
        /* Any TURN server to use in Janus? */
3562
        item = janus_config_get_item_drilldown(config, "nat", "turn_server");
3563
        if(item && item->value)
3564
                turn_server = (char *)item->value;
3565
        item = janus_config_get_item_drilldown(config, "nat", "turn_port");
3566
        if(item && item->value)
3567
                turn_port = atoi(item->value);
3568
        item = janus_config_get_item_drilldown(config, "nat", "turn_type");
3569
        if(item && item->value)
3570
                turn_type = (char *)item->value;
3571
        item = janus_config_get_item_drilldown(config, "nat", "turn_user");
3572
        if(item && item->value)
3573
                turn_user = (char *)item->value;
3574
        item = janus_config_get_item_drilldown(config, "nat", "turn_pwd");
3575
        if(item && item->value)
3576
                turn_pwd = (char *)item->value;
3577
        /* Check if there's any TURN REST API backend to use */
3578
        item = janus_config_get_item_drilldown(config, "nat", "turn_rest_api");
3579
        if(item && item->value)
3580
                turn_rest_api = (char *)item->value;
3581
        item = janus_config_get_item_drilldown(config, "nat", "turn_rest_api_key");
3582
        if(item && item->value)
3583
                turn_rest_api_key = (char *)item->value;
3584
#ifdef HAVE_LIBCURL
3585
        item = janus_config_get_item_drilldown(config, "nat", "turn_rest_api_method");
3586
        if(item && item->value)
3587
                turn_rest_api_method = (char *)item->value;
3588
#endif
3589
        /* Initialize the ICE stack now */
3590
        janus_ice_init(ice_lite, ice_tcp, ipv6, rtp_min_port, rtp_max_port);
3591
        if(janus_ice_set_stun_server(stun_server, stun_port) < 0) {
3592
                JANUS_LOG(LOG_FATAL, "Invalid STUN address %s:%u\n", stun_server, stun_port);
3593
                exit(1);
3594
        }
3595
        if(janus_ice_set_turn_server(turn_server, turn_port, turn_type, turn_user, turn_pwd) < 0) {
3596
                JANUS_LOG(LOG_FATAL, "Invalid TURN address %s:%u\n", turn_server, turn_port);
3597
                exit(1);
3598
        }
3599
#ifndef HAVE_LIBCURL
3600
        if(turn_rest_api != NULL || turn_rest_api_key != NULL) {
3601
                JANUS_LOG(LOG_WARN, "A TURN REST API backend specified in the settings, but libcurl support has not been built\n");
3602
        }
3603
#else
3604
        if(janus_ice_set_turn_rest_api(turn_rest_api, turn_rest_api_key, turn_rest_api_method) < 0) {
3605
                JANUS_LOG(LOG_FATAL, "Invalid TURN REST API configuration: %s (%s, %s)\n", turn_rest_api, turn_rest_api_key, turn_rest_api_method);
3606
                exit(1);
3607
        }
3608
#endif
3609
        item = janus_config_get_item_drilldown(config, "nat", "nice_debug");
3610
        if(item && item->value && janus_is_true(item->value)) {
3611
                /* Enable libnice debugging */
3612
                janus_ice_debugging_enable();
3613
        }
3614
        if(stun_server == NULL && turn_server == NULL) {
3615
                /* No STUN and TURN server provided for Janus: make sure it isn't on a private address */
3616
                gboolean private_address = FALSE;
3617
                const char *test_ip = nat_1_1_mapping ? nat_1_1_mapping : local_ip;
3618
                struct sockaddr_in addr;
3619
                if(inet_pton(AF_INET, test_ip, &addr) > 0) {
3620
                        unsigned short int ip[4];
3621
                        sscanf(test_ip, "%hu.%hu.%hu.%hu", &ip[0], &ip[1], &ip[2], &ip[3]);
3622
                        if(ip[0] == 10) {
3623
                                /* Class A private address */
3624
                                private_address = TRUE;
3625
                        } else if(ip[0] == 172 && (ip[1] >= 16 && ip[1] <= 31)) {
3626
                                /* Class B private address */
3627
                                private_address = TRUE;
3628
                        } else if(ip[0] == 192 && ip[1] == 168) {
3629
                                /* Class C private address */
3630
                                private_address = TRUE;
3631
                        }
3632
                }
3633
                if(private_address) {
3634
                        JANUS_LOG(LOG_WARN, "Janus is deployed on a private address (%s) but you didn't specify any STUN server!"
3635
                                            " Expect trouble if this is supposed to work over the internet and not just in a LAN...\n", test_ip);
3636
                }
3637
        }
3638
        /* Are we going to force BUNDLE and/or rtcp-mux? */
3639
        gboolean force_bundle = FALSE, force_rtcpmux = FALSE;
3640
        item = janus_config_get_item_drilldown(config, "media", "force-bundle");
3641
        force_bundle = (item && item->value) ? janus_is_true(item->value) : FALSE;
3642
        janus_ice_force_bundle(force_bundle);
3643
        item = janus_config_get_item_drilldown(config, "media", "force-rtcp-mux");
3644
        force_rtcpmux = (item && item->value) ? janus_is_true(item->value) : FALSE;
3645
        janus_ice_force_rtcpmux(force_rtcpmux);
3646
        /* NACK related stuff */
3647
        item = janus_config_get_item_drilldown(config, "media", "max_nack_queue");
3648
        if(item && item->value) {
3649
                int mnq = atoi(item->value);
3650
                if(mnq < 0) {
3651
                        JANUS_LOG(LOG_WARN, "Ignoring max_nack_queue value as it's not a positive integer\n");
3652
                } else if(mnq > 0 && mnq < 200) {
3653
                        JANUS_LOG(LOG_WARN, "Ignoring max_nack_queue value as it's less than 200\n");
3654
                } else {
3655
                        janus_set_max_nack_queue(mnq);
3656
                }
3657
        }
3658

    
3659
        /* Setup OpenSSL stuff */
3660
        const char* server_pem;
3661
        item = janus_config_get_item_drilldown(config, "certificates", "cert_pem");
3662
        if(!item || !item->value) {
3663
                server_pem = NULL;
3664
        } else {
3665
                server_pem = item->value;
3666
        }
3667

    
3668
        const char* server_key;
3669
        item = janus_config_get_item_drilldown(config, "certificates", "cert_key");
3670
        if(!item || !item->value) {
3671
                server_key = NULL;
3672
        } else {
3673
                server_key = item->value;
3674
        }
3675
        JANUS_LOG(LOG_VERB, "Using certificates:\n\t%s\n\t%s\n", server_pem, server_key);
3676

    
3677
        SSL_library_init();
3678
        SSL_load_error_strings();
3679
        OpenSSL_add_all_algorithms();
3680
        /* ... and DTLS-SRTP in particular */
3681
        if(janus_dtls_srtp_init(server_pem, server_key) < 0) {
3682
                exit(1);
3683
        }
3684
        /* Check if there's any custom value for the starting MTU to use in the BIO filter */
3685
        item = janus_config_get_item_drilldown(config, "media", "dtls_mtu");
3686
        if(item && item->value)
3687
                janus_dtls_bio_filter_set_mtu(atoi(item->value));
3688

    
3689
#ifdef HAVE_SCTP
3690
        /* Initialize SCTP for DataChannels */
3691
        if(janus_sctp_init() < 0) {
3692
                exit(1);
3693
        }
3694
#else
3695
        JANUS_LOG(LOG_WARN, "Data Channels support not compiled\n");
3696
#endif
3697

    
3698
        /* Sessions */
3699
        sessions = g_hash_table_new_full(g_int64_hash, g_int64_equal, (GDestroyNotify)g_free, NULL);
3700
        old_sessions = g_hash_table_new_full(g_int64_hash, g_int64_equal, (GDestroyNotify)g_free, NULL);
3701
        janus_mutex_init(&sessions_mutex);
3702
        /* Start the sessions watchdog */
3703
        sessions_watchdog_context = g_main_context_new();
3704
        GMainLoop *watchdog_loop = g_main_loop_new(sessions_watchdog_context, FALSE);
3705
        GError *error = NULL;
3706
        GThread *watchdog = g_thread_try_new("sessions watchdog", &janus_sessions_watchdog, watchdog_loop, &error);
3707
        if(error != NULL) {
3708
                JANUS_LOG(LOG_FATAL, "Got error %d (%s) trying to start sessions watchdog...\n", error->code, error->message ? error->message : "??");
3709
                exit(1);
3710
        }
3711

    
3712
        /* Load event handlers */
3713
        const char *path = EVENTDIR;
3714
        item = janus_config_get_item_drilldown(config, "general", "events_folder");
3715
        if(item && item->value)
3716
                path = (char *)item->value;
3717
        JANUS_LOG(LOG_INFO, "Event handler plugins folder: %s\n", path);
3718
        DIR *dir = opendir(path);
3719
        if(!dir) {
3720
                /* Not really fatal, we don't care and go on anyway: event handlers are not fundamental */
3721
                JANUS_LOG(LOG_FATAL, "\tCouldn't access event handler plugins folder...\n");
3722
        } else {
3723
                /* Any event handlers to ignore? */
3724
                gchar **disabled_eventhandlers = NULL;
3725
                item = janus_config_get_item_drilldown(config, "events", "broadcast");
3726
                /* Event handlers are disabled by default: they need to be enabled in the configuration */
3727
                gboolean enable_events = FALSE;
3728
                if(item && item->value)
3729
                        enable_events = janus_is_true(item->value);
3730
                if(!enable_events) {
3731
                        JANUS_LOG(LOG_WARN, "Event handlers support disabled\n");
3732
                } else {
3733
                        item = janus_config_get_item_drilldown(config, "events", "disable");
3734
                        if(item && item->value)
3735
                                disabled_eventhandlers = g_strsplit(item->value, ",", -1);
3736
                        /* Open the shared objects */
3737
                        struct dirent *eventent = NULL;
3738
                        char eventpath[1024];
3739
                        while((eventent = readdir(dir))) {
3740
                                int len = strlen(eventent->d_name);
3741
                                if (len < 4) {
3742
                                        continue;
3743
                                }
3744
                                if (strcasecmp(eventent->d_name+len-strlen(SHLIB_EXT), SHLIB_EXT)) {
3745
                                        continue;
3746
                                }
3747
                                /* Check if this event handler has been disabled in the configuration file */
3748
                                if(disabled_eventhandlers != NULL) {
3749
                                        gchar *index = disabled_eventhandlers[0];
3750
                                        if(index != NULL) {
3751
                                                int i=0;
3752
                                                gboolean skip = FALSE;
3753
                                                while(index != NULL) {
3754
                                                        while(isspace(*index))
3755
                                                                index++;
3756
                                                        if(strlen(index) && !strcmp(index, eventent->d_name)) {
3757
                                                                JANUS_LOG(LOG_WARN, "Event handler plugin '%s' has been disabled, skipping...\n", eventent->d_name);
3758
                                                                skip = TRUE;
3759
                                                                break;
3760
                                                        }
3761
                                                        i++;
3762
                                                        index = disabled_eventhandlers[i];
3763
                                                }
3764
                                                if(skip)
3765
                                                        continue;
3766
                                        }
3767
                                }
3768
                                JANUS_LOG(LOG_INFO, "Loading event handler plugin '%s'...\n", eventent->d_name);
3769
                                memset(eventpath, 0, 1024);
3770
                                g_snprintf(eventpath, 1024, "%s/%s", path, eventent->d_name);
3771
                                void *event = dlopen(eventpath, RTLD_LAZY);
3772
                                if (!event) {
3773
                                        JANUS_LOG(LOG_ERR, "\tCouldn't load event handler plugin '%s': %s\n", eventent->d_name, dlerror());
3774
                                } else {
3775
                                        create_e *create = (create_e*) dlsym(event, "create");
3776
                                        const char *dlsym_error = dlerror();
3777
                                        if (dlsym_error) {
3778
                                                JANUS_LOG(LOG_ERR, "\tCouldn't load symbol 'create': %s\n", dlsym_error);
3779
                                                continue;
3780
                                        }
3781
                                        janus_eventhandler *janus_eventhandler = create();
3782
                                        if(!janus_eventhandler) {
3783
                                                JANUS_LOG(LOG_ERR, "\tCouldn't use function 'create'...\n");
3784
                                                continue;
3785
                                        }
3786
                                        /* Are all the mandatory methods and callbacks implemented? */
3787
                                        if(!janus_eventhandler->init || !janus_eventhandler->destroy ||
3788
                                                        !janus_eventhandler->get_api_compatibility ||
3789
                                                        !janus_eventhandler->get_version ||
3790
                                                        !janus_eventhandler->get_version_string ||
3791
                                                        !janus_eventhandler->get_description ||
3792
                                                        !janus_eventhandler->get_package ||
3793
                                                        !janus_eventhandler->get_name ||
3794
                                                        !janus_eventhandler->incoming_event) {
3795
                                                JANUS_LOG(LOG_ERR, "\tMissing some mandatory methods/callbacks, skipping this event handler plugin...\n");
3796
                                                continue;
3797
                                        }
3798
                                        if(janus_eventhandler->get_api_compatibility() < JANUS_EVENTHANDLER_API_VERSION) {
3799
                                                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",
3800
                                                        janus_eventhandler->get_package(), janus_eventhandler->get_api_compatibility(), JANUS_EVENTHANDLER_API_VERSION);
3801
                                                continue;
3802
                                        }
3803
                                        janus_eventhandler->init(configs_folder);
3804
                                        JANUS_LOG(LOG_VERB, "\tVersion: %d (%s)\n", janus_eventhandler->get_version(), janus_eventhandler->get_version_string());
3805
                                        JANUS_LOG(LOG_VERB, "\t   [%s] %s\n", janus_eventhandler->get_package(), janus_eventhandler->get_name());
3806
                                        JANUS_LOG(LOG_VERB, "\t   %s\n", janus_eventhandler->get_description());
3807
                                        JANUS_LOG(LOG_VERB, "\t   Plugin API version: %d\n", janus_eventhandler->get_api_compatibility());
3808
                                        JANUS_LOG(LOG_VERB, "\t   Subscriptions:");
3809
                                        if(janus_eventhandler->events_mask == 0) {
3810
                                                JANUS_LOG(LOG_VERB, " none");
3811
                                        } else {
3812
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_SESSION))
3813
                                                        JANUS_LOG(LOG_VERB, " sessions");
3814
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_HANDLE))
3815
                                                        JANUS_LOG(LOG_VERB, " handles");
3816
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_JSEP))
3817
                                                        JANUS_LOG(LOG_VERB, " jsep");
3818
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_WEBRTC))
3819
                                                        JANUS_LOG(LOG_VERB, " webrtc");
3820
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_MEDIA))
3821
                                                        JANUS_LOG(LOG_VERB, " media");
3822
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_PLUGIN))
3823
                                                        JANUS_LOG(LOG_VERB, " plugins");
3824
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_TRANSPORT))
3825
                                                        JANUS_LOG(LOG_VERB, " transports");
3826
                                        }
3827
                                        JANUS_LOG(LOG_VERB, "\n");
3828
                                        if(eventhandlers == NULL)
3829
                                                eventhandlers = g_hash_table_new(g_str_hash, g_str_equal);
3830
                                        g_hash_table_insert(eventhandlers, (gpointer)janus_eventhandler->get_package(), janus_eventhandler);
3831
                                        if(eventhandlers_so == NULL)
3832
                                                eventhandlers_so = g_hash_table_new(g_str_hash, g_str_equal);
3833
                                        g_hash_table_insert(eventhandlers_so, (gpointer)janus_eventhandler->get_package(), event);
3834
                                }
3835
                        }
3836
                }
3837
                closedir(dir);
3838
                if(disabled_eventhandlers != NULL)
3839
                        g_strfreev(disabled_eventhandlers);
3840
                disabled_eventhandlers = NULL;
3841
                /* Initialize the event broadcaster */
3842
                if(janus_events_init(enable_events, eventhandlers) < 0) {
3843
                        JANUS_LOG(LOG_FATAL, "Error initializing the Event handlers mechanism...\n");
3844
                        exit(1);
3845
                }
3846
        }
3847

    
3848
        /* Load plugins */
3849
        path = PLUGINDIR;
3850
        item = janus_config_get_item_drilldown(config, "general", "plugins_folder");
3851
        if(item && item->value)
3852
                path = (char *)item->value;
3853
        JANUS_LOG(LOG_INFO, "Plugins folder: %s\n", path);
3854
        dir = opendir(path);
3855
        if(!dir) {
3856
                JANUS_LOG(LOG_FATAL, "\tCouldn't access plugins folder...\n");
3857
                exit(1);
3858
        }
3859
        /* Any plugin to ignore? */
3860
        gchar **disabled_plugins = NULL;
3861
        item = janus_config_get_item_drilldown(config, "plugins", "disable");
3862
        if(item && item->value)
3863
                disabled_plugins = g_strsplit(item->value, ",", -1);
3864
        /* Open the shared objects */
3865
        struct dirent *pluginent = NULL;
3866
        char pluginpath[1024];
3867
        while((pluginent = readdir(dir))) {
3868
                int len = strlen(pluginent->d_name);
3869
                if (len < 4) {
3870
                        continue;
3871
                }
3872
                if (strcasecmp(pluginent->d_name+len-strlen(SHLIB_EXT), SHLIB_EXT)) {
3873
                        continue;
3874
                }
3875
                /* Check if this plugins has been disabled in the configuration file */
3876
                if(disabled_plugins != NULL) {
3877
                        gchar *index = disabled_plugins[0];
3878
                        if(index != NULL) {
3879
                                int i=0;
3880
                                gboolean skip = FALSE;
3881
                                while(index != NULL) {
3882
                                        while(isspace(*index))
3883
                                                index++;
3884
                                        if(strlen(index) && !strcmp(index, pluginent->d_name)) {
3885
                                                JANUS_LOG(LOG_WARN, "Plugin '%s' has been disabled, skipping...\n", pluginent->d_name);
3886
                                                skip = TRUE;
3887
                                                break;
3888
                                        }
3889
                                        i++;
3890
                                        index = disabled_plugins[i];
3891
                                }
3892
                                if(skip)
3893
                                        continue;
3894
                        }
3895
                }
3896
                JANUS_LOG(LOG_INFO, "Loading plugin '%s'...\n", pluginent->d_name);
3897
                memset(pluginpath, 0, 1024);
3898
                g_snprintf(pluginpath, 1024, "%s/%s", path, pluginent->d_name);
3899
                void *plugin = dlopen(pluginpath, RTLD_LOCAL | RTLD_LAZY);
3900
                if (!plugin) {
3901
                        JANUS_LOG(LOG_ERR, "\tCouldn't load plugin '%s': %s\n", pluginent->d_name, dlerror());
3902
                } else {
3903
                        create_p *create = (create_p*) dlsym(plugin, "create");
3904
                        const char *dlsym_error = dlerror();
3905
                        if (dlsym_error) {
3906
                                JANUS_LOG(LOG_ERR, "\tCouldn't load symbol 'create': %s\n", dlsym_error);
3907
                                continue;
3908
                        }
3909
                        janus_plugin *janus_plugin = create();
3910
                        if(!janus_plugin) {
3911
                                JANUS_LOG(LOG_ERR, "\tCouldn't use function 'create'...\n");
3912
                                continue;
3913
                        }
3914
                        /* Are all the mandatory methods and callbacks implemented? */
3915
                        if(!janus_plugin->init || !janus_plugin->destroy ||
3916
                                        !janus_plugin->get_api_compatibility ||
3917
                                        !janus_plugin->get_version ||
3918
                                        !janus_plugin->get_version_string ||
3919
                                        !janus_plugin->get_description ||
3920
                                        !janus_plugin->get_package ||
3921
                                        !janus_plugin->get_name ||
3922
                                        !janus_plugin->create_session ||
3923
                                        !janus_plugin->query_session ||
3924
                                        !janus_plugin->destroy_session ||
3925
                                        !janus_plugin->handle_message ||
3926
                                        !janus_plugin->setup_media ||
3927
                                        !janus_plugin->hangup_media) {
3928
                                JANUS_LOG(LOG_ERR, "\tMissing some mandatory methods/callbacks, skipping this plugin...\n");
3929
                                continue;
3930
                        }
3931
                        if(janus_plugin->get_api_compatibility() < JANUS_PLUGIN_API_VERSION) {
3932
                                JANUS_LOG(LOG_ERR, "The '%s' plugin was compiled against an older version of the API (%d < %d), skipping it: update it to enable it again\n",
3933
                                        janus_plugin->get_package(), janus_plugin->get_api_compatibility(), JANUS_PLUGIN_API_VERSION);
3934
                                continue;
3935
                        }
3936
                        if(janus_plugin->init(&janus_handler_plugin, configs_folder) < 0) {
3937
                                JANUS_LOG(LOG_WARN, "The '%s' plugin could not be initialized\n", janus_plugin->get_package());
3938
                                dlclose(plugin);
3939
                                continue;
3940
                        }
3941
                        JANUS_LOG(LOG_VERB, "\tVersion: %d (%s)\n", janus_plugin->get_version(), janus_plugin->get_version_string());
3942
                        JANUS_LOG(LOG_VERB, "\t   [%s] %s\n", janus_plugin->get_package(), janus_plugin->get_name());
3943
                        JANUS_LOG(LOG_VERB, "\t   %s\n", janus_plugin->get_description());
3944
                        JANUS_LOG(LOG_VERB, "\t   Plugin API version: %d\n", janus_plugin->get_api_compatibility());
3945
                        if(!janus_plugin->incoming_rtp && !janus_plugin->incoming_rtcp && !janus_plugin->incoming_data) {
3946
                                JANUS_LOG(LOG_WARN, "The '%s' plugin doesn't implement any callback for RTP/RTCP/data... is this on purpose?\n",
3947
                                        janus_plugin->get_package());
3948
                        }
3949
                        if(!janus_plugin->incoming_rtp && !janus_plugin->incoming_rtcp && janus_plugin->incoming_data) {
3950
                                JANUS_LOG(LOG_WARN, "The '%s' plugin will only handle data channels (no RTP/RTCP)... is this on purpose?\n",
3951
                                        janus_plugin->get_package());
3952
                        }
3953
                        if(plugins == NULL)
3954
                                plugins = g_hash_table_new(g_str_hash, g_str_equal);
3955
                        g_hash_table_insert(plugins, (gpointer)janus_plugin->get_package(), janus_plugin);
3956
                        if