Statistics
| Branch: | Revision:

janus-gateway / janus.c @ 1d31e31f

History | View | Annotate | Download (174 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 "sdp.h"
36
#include "auth.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                        10
43
#define JANUS_VERSION_STRING        "0.1.0"
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
/* Certificates */
73
static char *server_pem = NULL;
74
gchar *janus_get_server_pem(void) {
75
        return server_pem;
76
}
77
static char *server_key = NULL;
78
gchar *janus_get_server_key(void) {
79
        return server_key;
80
}
81

    
82

    
83
/* API secrets */
84
static char *api_secret = NULL, *admin_api_secret = NULL;
85

    
86
/* JSON parameters */
87
static int janus_process_error_string(janus_request *request, uint64_t session_id, const char *transaction, gint error, gchar *error_string);
88

    
89
static struct janus_json_parameter incoming_request_parameters[] = {
90
        {"transaction", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
91
        {"janus", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
92
        {"id", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE}
93
};
94
static struct janus_json_parameter attach_parameters[] = {
95
        {"plugin", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
96
};
97
static struct janus_json_parameter jsep_parameters[] = {
98
        {"type", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
99
        {"trickle", JANUS_JSON_BOOL, 0},
100
        {"sdp", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
101
};
102

    
103
/* Admin/Monitor helpers */
104
json_t *janus_admin_stream_summary(janus_ice_stream *stream);
105
json_t *janus_admin_component_summary(janus_ice_component *component);
106

    
107

    
108
/* IP addresses */
109
static gchar local_ip[INET6_ADDRSTRLEN];
110
gchar *janus_get_local_ip(void) {
111
        return local_ip;
112
}
113
static gchar *public_ip = NULL;
114
gchar *janus_get_public_ip(void) {
115
        /* Fallback to the local IP, if we have no public one */
116
        return public_ip ? public_ip : local_ip;
117
}
118
void janus_set_public_ip(const char *ip) {
119
        /* once set do not override */
120
        if(ip == NULL || public_ip != NULL)
121
                return;
122
        public_ip = g_strdup(ip);
123
}
124
static volatile gint stop = 0;
125
gint janus_is_stopping(void) {
126
        return g_atomic_int_get(&stop);
127
}
128

    
129

    
130
/* Public instance name */
131
static gchar *server_name = NULL;
132

    
133

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

    
241

    
242
/* Logging */
243
int janus_log_level = LOG_INFO;
244
gboolean janus_log_timestamps = FALSE;
245
gboolean janus_log_colors = FALSE;
246
int lock_debug = 0;
247

    
248

    
249
/*! \brief Signal handler (just used to intercept CTRL+C and SIGTERM) */
250
static void janus_handle_signal(int signum) {
251
        switch(g_atomic_int_get(&stop)) {
252
                case 0:
253
                        JANUS_PRINT("Stopping gateway, please wait...\n");
254
                        break;
255
                case 1:
256
                        JANUS_PRINT("In a hurry? I'm trying to free resources cleanly, here!\n");
257
                        break;
258
                default:
259
                        JANUS_PRINT("Ok, leaving immediately...\n");
260
                        break;
261
        }
262
        g_atomic_int_inc(&stop);
263
        if(g_atomic_int_get(&stop) > 2)
264
                exit(1);
265
}
266

    
267
/*! \brief Termination handler (atexit) */
268
static void janus_termination_handler(void) {
269
        /* Free the instance name, if provided */
270
        g_free(server_name);
271
        /* Remove the PID file if we created it */
272
        janus_pidfile_remove();
273
        /* Close the logger */
274
        janus_log_destroy();
275
        /* If we're daemonizing, we send an error code to the parent */
276
        if(daemonize) {
277
                int code = 1;
278
                ssize_t res = 0;
279
                do {
280
                        res = write(pipefd[1], &code, sizeof(int));
281
                } while(res == -1 && errno == EINTR);
282
        }
283
}
284

    
285

    
286
/** @name Transport plugin callback interface
287
 * These are the callbacks implemented by the gateway core, as part of
288
 * the janus_transport_callbacks interface. Everything the transport
289
 * plugins send the gateway is handled here.
290
 */
291
///@{
292
void janus_transport_incoming_request(janus_transport *plugin, void *transport, void *request_id, gboolean admin, json_t *message, json_error_t *error);
293
void janus_transport_gone(janus_transport *plugin, void *transport);
294
gboolean janus_transport_is_api_secret_needed(janus_transport *plugin);
295
gboolean janus_transport_is_api_secret_valid(janus_transport *plugin, const char *apisecret);
296
gboolean janus_transport_is_auth_token_needed(janus_transport *plugin);
297
gboolean janus_transport_is_auth_token_valid(janus_transport *plugin, const char *token);
298

    
299
static janus_transport_callbacks janus_handler_transport =
300
        {
301
                .incoming_request = janus_transport_incoming_request,
302
                .transport_gone = janus_transport_gone,
303
                .is_api_secret_needed = janus_transport_is_api_secret_needed,
304
                .is_api_secret_valid = janus_transport_is_api_secret_valid,
305
                .is_auth_token_needed = janus_transport_is_auth_token_needed,
306
                .is_auth_token_valid = janus_transport_is_auth_token_valid,
307
        }; 
308
GThreadPool *tasks = NULL;
309
void janus_transport_task(gpointer data, gpointer user_data);
310
///@}
311

    
312

    
313
/** @name Plugin callback interface
314
 * These are the callbacks implemented by the gateway core, as part of
315
 * the janus_callbacks interface. Everything the plugins send the
316
 * gateway is handled here.
317
 */
318
///@{
319
int janus_plugin_push_event(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *transaction, const char *message, const char *sdp_type, const char *sdp);
320
json_t *janus_plugin_handle_sdp(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *sdp_type, const char *sdp);
321
void janus_plugin_relay_rtp(janus_plugin_session *plugin_session, int video, char *buf, int len);
322
void janus_plugin_relay_rtcp(janus_plugin_session *plugin_session, int video, char *buf, int len);
323
void janus_plugin_relay_data(janus_plugin_session *plugin_session, char *buf, int len);
324
void janus_plugin_close_pc(janus_plugin_session *plugin_session);
325
void janus_plugin_end_session(janus_plugin_session *plugin_session);
326
void janus_plugin_notify_event(janus_plugin_session *plugin_session, json_t *event);
327
static janus_callbacks janus_handler_plugin =
328
        {
329
                .push_event = janus_plugin_push_event,
330
                .relay_rtp = janus_plugin_relay_rtp,
331
                .relay_rtcp = janus_plugin_relay_rtcp,
332
                .relay_data = janus_plugin_relay_data,
333
                .close_pc = janus_plugin_close_pc,
334
                .end_session = janus_plugin_end_session,
335
                .events_is_enabled = janus_events_is_enabled,
336
                .notify_event = janus_plugin_notify_event,
337
        }; 
338
///@}
339

    
340

    
341
/* Gateway Sessions */
342
static janus_mutex sessions_mutex;
343
static GHashTable *sessions = NULL, *old_sessions = NULL;
344
static GMainContext *sessions_watchdog_context = NULL;
345

    
346

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

    
349
static gboolean janus_cleanup_session(gpointer user_data) {
350
        janus_session *session = (janus_session *) user_data;
351

    
352
        JANUS_LOG(LOG_DBG, "Cleaning up session %"SCNu64"...\n", session->session_id);
353
        janus_session_destroy(session->session_id);
354

    
355
        return G_SOURCE_REMOVE;
356
}
357

    
358
static gboolean janus_check_sessions(gpointer user_data) {
359
        GMainContext *watchdog_context = (GMainContext *) user_data;
360
        janus_mutex_lock(&sessions_mutex);
361
        if(sessions && g_hash_table_size(sessions) > 0) {
362
                GHashTableIter iter;
363
                gpointer value;
364
                g_hash_table_iter_init(&iter, sessions);
365
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
366
                        janus_session *session = (janus_session *) value;
367
                        if (!session || session->destroy) {
368
                                continue;
369
                        }
370
                        gint64 now = janus_get_monotonic_time();
371
                        if (now - session->last_activity >= SESSION_TIMEOUT * G_USEC_PER_SEC && !session->timeout) {
372
                                JANUS_LOG(LOG_INFO, "Timeout expired for session %"SCNu64"...\n", session->session_id);
373

    
374
                                /* Notify the transport */
375
                                if(session->source) {
376
                                        json_t *event = json_object();
377
                                        json_object_set_new(event, "janus", json_string("timeout"));
378
                                        json_object_set_new(event, "session_id", json_integer(session->session_id));
379
                                        /* Send this to the transport client */
380
                                        session->source->transport->send_message(session->source->instance, NULL, FALSE, event);
381
                                        /* Notify the transport plugin about the session timeout */
382
                                        session->source->transport->session_over(session->source->instance, session->session_id, TRUE);
383
                                }
384
                                /* Notify event handlers as well */
385
                                if(janus_events_is_enabled())
386
                                        janus_events_notify_handlers(JANUS_EVENT_TYPE_SESSION, session->session_id, "timeout");
387

    
388
                                /* Mark the session as over, we'll deal with it later */
389
                                session->timeout = 1;
390
                                /* FIXME Is this safe? apparently it causes hash table errors on the console */
391
                                g_hash_table_iter_remove(&iter);
392
                                g_hash_table_insert(old_sessions, GUINT_TO_POINTER(session->session_id), session);
393

    
394
                                /* Schedule the session for deletion */
395
                                GSource *timeout_source = g_timeout_source_new_seconds(3);
396
                                g_source_set_callback(timeout_source, janus_cleanup_session, session, NULL);
397
                                g_source_attach(timeout_source, watchdog_context);
398
                                g_source_unref(timeout_source);
399
                        }
400
                }
401
        }
402
        janus_mutex_unlock(&sessions_mutex);
403

    
404
        return G_SOURCE_CONTINUE;
405
}
406

    
407
static gpointer janus_sessions_watchdog(gpointer user_data) {
408
        GMainLoop *loop = (GMainLoop *) user_data;
409
        GMainContext *watchdog_context = g_main_loop_get_context(loop);
410
        GSource *timeout_source;
411

    
412
        timeout_source = g_timeout_source_new_seconds(2);
413
        g_source_set_callback(timeout_source, janus_check_sessions, watchdog_context, NULL);
414
        g_source_attach(timeout_source, watchdog_context);
415
        g_source_unref(timeout_source);
416

    
417
        JANUS_LOG(LOG_INFO, "Sessions watchdog started\n");
418

    
419
        g_main_loop_run(loop);
420

    
421
        return NULL;
422
}
423

    
424
janus_session *janus_session_create(guint64 session_id) {
425
        if(session_id == 0) {
426
                while(session_id == 0) {
427
                        session_id = g_random_int();
428
                        if(janus_session_find(session_id) != NULL) {
429
                                /* Session ID already taken, try another one */
430
                                session_id = 0;
431
                        }
432
                }
433
        }
434
        JANUS_LOG(LOG_INFO, "Creating new session: %"SCNu64"\n", session_id);
435
        janus_session *session = (janus_session *)g_malloc0(sizeof(janus_session));
436
        if(session == NULL) {
437
                JANUS_LOG(LOG_FATAL, "Memory error!\n");
438
                return NULL;
439
        }
440
        session->session_id = session_id;
441
        session->source = NULL;
442
        session->destroy = 0;
443
        session->timeout = 0;
444
        session->last_activity = janus_get_monotonic_time();
445
        janus_mutex_init(&session->mutex);
446
        janus_mutex_lock(&sessions_mutex);
447
        g_hash_table_insert(sessions, GUINT_TO_POINTER(session_id), session);
448
        janus_mutex_unlock(&sessions_mutex);
449
        /* Notify event handlers */
450
        if(janus_events_is_enabled())
451
                janus_events_notify_handlers(JANUS_EVENT_TYPE_SESSION, session_id, "created");
452
        return session;
453
}
454

    
455
janus_session *janus_session_find(guint64 session_id) {
456
        janus_mutex_lock(&sessions_mutex);
457
        janus_session *session = g_hash_table_lookup(sessions, GUINT_TO_POINTER(session_id));
458
        janus_mutex_unlock(&sessions_mutex);
459
        return session;
460
}
461

    
462
janus_session *janus_session_find_destroyed(guint64 session_id) {
463
        janus_mutex_lock(&sessions_mutex);
464
        janus_session *session = g_hash_table_lookup(old_sessions, GUINT_TO_POINTER(session_id));
465
        janus_mutex_unlock(&sessions_mutex);
466
        return session;
467
}
468

    
469
void janus_session_notify_event(guint64 session_id, json_t *event) {
470
        janus_mutex_lock(&sessions_mutex);
471
        janus_session *session = sessions ? g_hash_table_lookup(sessions, GUINT_TO_POINTER(session_id)) : NULL;
472
        if(session != NULL && !session->destroy && session->source != NULL && session->source->transport != NULL) {
473
                janus_mutex_unlock(&sessions_mutex);
474
                /* Send this to the transport client */
475
                JANUS_LOG(LOG_HUGE, "Sending event to %s (%p)\n", session->source->transport->get_package(), session->source->instance);
476
                session->source->transport->send_message(session->source->instance, NULL, FALSE, event);
477
        } else {
478
                janus_mutex_unlock(&sessions_mutex);
479
                /* No transport, free the event */
480
                json_decref(event);
481
        }
482
}
483

    
484

    
485
/* Destroys a session but does not remove it from the sessions hash table. */
486
gint janus_session_destroy(guint64 session_id) {
487
        janus_session *session = janus_session_find_destroyed(session_id);
488
        if(session == NULL) {
489
                JANUS_LOG(LOG_ERR, "Couldn't find session to destroy: %"SCNu64"\n", session_id);
490
                return -1;
491
        }
492
        JANUS_LOG(LOG_VERB, "Destroying session %"SCNu64"\n", session_id);
493
        session->destroy = 1;
494
        if (session->ice_handles != NULL && g_hash_table_size(session->ice_handles) > 0) {
495
                GHashTableIter iter;
496
                gpointer value;
497
                /* Remove all handles */
498
                g_hash_table_iter_init(&iter, session->ice_handles);
499
                while (g_hash_table_iter_next(&iter, NULL, &value)) {
500
                        janus_ice_handle *handle = value;
501
                        if(!handle || g_atomic_int_get(&stop)) {
502
                                continue;
503
                        }
504
                        janus_ice_handle_destroy(session, handle->handle_id);
505
                        g_hash_table_iter_remove(&iter);
506
                }
507
        }
508

    
509
        /* FIXME Actually destroy session */
510
        janus_session_free(session);
511

    
512
        return 0;
513
}
514

    
515
void janus_session_free(janus_session *session) {
516
        if(session == NULL)
517
                return;
518
        janus_mutex_lock(&session->mutex);
519
        if(session->ice_handles != NULL) {
520
                g_hash_table_destroy(session->ice_handles);
521
                session->ice_handles = NULL;
522
        }
523
        if(session->source != NULL) {
524
                janus_request_destroy(session->source);
525
                session->source = NULL;
526
        }
527
        janus_mutex_unlock(&session->mutex);
528
        g_free(session);
529
        session = NULL;
530
}
531

    
532

    
533
/* Requests management */
534
janus_request *janus_request_new(janus_transport *transport, void *instance, void *request_id, gboolean admin, json_t *message) {
535
        janus_request *request = (janus_request *)g_malloc0(sizeof(janus_request));
536
        request->transport = transport;
537
        request->instance = instance;
538
        request->request_id = request_id;
539
        request->admin = admin;
540
        request->message = message;
541
        return request;
542
}
543

    
544
void janus_request_destroy(janus_request *request) {
545
        if(request == NULL)
546
                return;
547
        request->transport = NULL;
548
        request->instance = NULL;
549
        request->request_id = NULL;
550
        if(request->message)
551
                json_decref(request->message);
552
        request->message = NULL;
553
        g_free(request);
554
}
555

    
556
int janus_process_incoming_request(janus_request *request) {
557
        int ret = -1;
558
        if(request == NULL) {
559
                JANUS_LOG(LOG_ERR, "Missing request or payload to process, giving up...\n");
560
                return ret;
561
        }
562
        int error_code = 0;
563
        char error_cause[100];
564
        json_t *root = request->message;
565
        /* Ok, let's start with the ids */
566
        guint64 session_id = 0, handle_id = 0;
567
        json_t *s = json_object_get(root, "session_id");
568
        if(s && json_is_integer(s))
569
                session_id = json_integer_value(s);
570
        json_t *h = json_object_get(root, "handle_id");
571
        if(h && json_is_integer(h))
572
                handle_id = json_integer_value(h);
573

    
574
        /* Get transaction and message request */
575
        JANUS_VALIDATE_JSON_OBJECT(root, incoming_request_parameters,
576
                error_code, error_cause, FALSE,
577
                JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
578
        if(error_code != 0) {
579
                ret = janus_process_error_string(request, session_id, NULL, error_code, error_cause);
580
                goto jsondone;
581
        }
582
        json_t *transaction = json_object_get(root, "transaction");
583
        const gchar *transaction_text = json_string_value(transaction);
584
        json_t *message = json_object_get(root, "janus");
585
        const gchar *message_text = json_string_value(message);
586
        
587
        if(session_id == 0 && handle_id == 0) {
588
                /* Can only be a 'Create new session', a 'Get info' or a 'Ping/Pong' request */
589
                if(!strcasecmp(message_text, "info")) {
590
                        ret = janus_process_success(request, janus_info(transaction_text));
591
                        goto jsondone;
592
                }
593
                if(!strcasecmp(message_text, "ping")) {
594
                        /* Prepare JSON reply */
595
                        json_t *reply = json_object();
596
                        json_object_set_new(reply, "janus", json_string("pong"));
597
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
598
                        ret = janus_process_success(request, reply);
599
                        goto jsondone;
600
                }
601
                if(strcasecmp(message_text, "create")) {
602
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
603
                        goto jsondone;
604
                }
605
                /* Any secret/token to check? */
606
                gboolean secret_authorized = FALSE, token_authorized = FALSE;
607
                if(api_secret == NULL && !janus_auth_is_enabled()) {
608
                        /* Nothing to check */
609
                        secret_authorized = TRUE;
610
                        token_authorized = TRUE;
611
                } else {
612
                        if(api_secret != NULL) {
613
                                /* There's an API secret, check that the client provided it */
614
                                json_t *secret = json_object_get(root, "apisecret");
615
                                if(secret && json_is_string(secret) && janus_strcmp_const_time(json_string_value(secret), api_secret)) {
616
                                        secret_authorized = TRUE;
617
                                }
618
                        }
619
                        if(janus_auth_is_enabled()) {
620
                                /* The token based authentication mechanism is enabled, check that the client provided it */
621
                                json_t *token = json_object_get(root, "token");
622
                                if(token && json_is_string(token) && janus_auth_check_token(json_string_value(token))) {
623
                                        token_authorized = TRUE;
624
                                }
625
                        }
626
                        /* We consider a request authorized if either the proper API secret or a valid token has been provided */
627
                        if(!secret_authorized && !token_authorized) {
628
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNAUTHORIZED, NULL);
629
                                goto jsondone;
630
                        }
631
                }
632
                session_id = 0;
633
                json_t *id = json_object_get(root, "id");
634
                if(id != NULL) {
635
                        /* The application provided the session ID to use */
636
                        session_id = json_integer_value(id);
637
                        if(session_id > 0 && janus_session_find(session_id) != NULL) {
638
                                /* Session ID already taken */
639
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_CONFLICT, "Session ID already in use");
640
                                goto jsondone;
641
                        }
642
                }
643
                /* Handle it */
644
                janus_session *session = janus_session_create(session_id);
645
                if(session == NULL) {
646
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN, "Memory error");
647
                        goto jsondone;
648
                }
649
                session_id = session->session_id;
650
                /* Take note of the request source that originated this session (HTTP, WebSockets, RabbitMQ?) */
651
                session->source = janus_request_new(request->transport, request->instance, NULL, FALSE, NULL);
652
                /* Notify the source that a new session has been created */
653
                request->transport->session_created(request->instance, session->session_id);
654
                /* Prepare JSON reply */
655
                json_t *reply = json_object();
656
                json_object_set_new(reply, "janus", json_string("success"));
657
                json_object_set_new(reply, "transaction", json_string(transaction_text));
658
                json_t *data = json_object();
659
                json_object_set_new(data, "id", json_integer(session_id));
660
                json_object_set_new(reply, "data", data);
661
                /* Send the success reply */
662
                ret = janus_process_success(request, reply);
663
                goto jsondone;
664
        }
665
        if(session_id < 1) {
666
                JANUS_LOG(LOG_ERR, "Invalid session\n");
667
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, NULL);
668
                goto jsondone;
669
        }
670
        if(h && handle_id < 1) {
671
                JANUS_LOG(LOG_ERR, "Invalid handle\n");
672
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, NULL);
673
                goto jsondone;
674
        }
675

    
676
        /* Go on with the processing */
677
        gboolean secret_authorized = FALSE, token_authorized = FALSE;
678
        if(api_secret == NULL && !janus_auth_is_enabled()) {
679
                /* Nothing to check */
680
                secret_authorized = TRUE;
681
                token_authorized = TRUE;
682
        } else {
683
                if(api_secret != NULL) {
684
                        /* There's an API secret, check that the client provided it */
685
                        json_t *secret = json_object_get(root, "apisecret");
686
                        if(secret && json_is_string(secret) && janus_strcmp_const_time(json_string_value(secret), api_secret)) {
687
                                secret_authorized = TRUE;
688
                        }
689
                }
690
                if(janus_auth_is_enabled()) {
691
                        /* The token based authentication mechanism is enabled, check that the client provided it */
692
                        json_t *token = json_object_get(root, "token");
693
                        if(token && json_is_string(token) && janus_auth_check_token(json_string_value(token))) {
694
                                token_authorized = TRUE;
695
                        }
696
                }
697
                /* We consider a request authorized if either the proper API secret or a valid token has been provided */
698
                if(!secret_authorized && !token_authorized) {
699
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNAUTHORIZED, NULL);
700
                        goto jsondone;
701
                }
702
        }
703

    
704
        /* If we got here, make sure we have a session (and/or a handle) */
705
        janus_session *session = janus_session_find(session_id);
706
        if(!session) {
707
                JANUS_LOG(LOG_ERR, "Couldn't find any session %"SCNu64"...\n", session_id);
708
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_SESSION_NOT_FOUND, "No such session %"SCNu64"", session_id);
709
                goto jsondone;
710
        }
711
        /* Update the last activity timer */
712
        session->last_activity = janus_get_monotonic_time();
713
        janus_ice_handle *handle = NULL;
714
        if(handle_id > 0) {
715
                handle = janus_ice_handle_find(session, handle_id);
716
                if(!handle) {
717
                        JANUS_LOG(LOG_ERR, "Couldn't find any handle %"SCNu64" in session %"SCNu64"...\n", handle_id, session_id);
718
                        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);
719
                        goto jsondone;
720
                }
721
        }
722

    
723
        /* What is this? */
724
        if(!strcasecmp(message_text, "keepalive")) {
725
                /* Just a keep-alive message, reply with an ack */
726
                JANUS_LOG(LOG_VERB, "Got a keep-alive on session %"SCNu64"\n", session_id);
727
                json_t *reply = json_object();
728
                json_object_set_new(reply, "janus", json_string("ack"));
729
                json_object_set_new(reply, "session_id", json_integer(session_id));
730
                json_object_set_new(reply, "transaction", json_string(transaction_text));
731
                /* Send the success reply */
732
                ret = janus_process_success(request, reply);
733
        } else if(!strcasecmp(message_text, "attach")) {
734
                if(handle != NULL) {
735
                        /* Attach is a session-level command */
736
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
737
                        goto jsondone;
738
                }
739
                JANUS_VALIDATE_JSON_OBJECT(root, attach_parameters,
740
                        error_code, error_cause, FALSE,
741
                        JANUS_ERROR_MISSING_MANDATORY_ELEMENT, JANUS_ERROR_INVALID_ELEMENT_TYPE);
742
                if(error_code != 0) {
743
                        ret = janus_process_error_string(request, session_id, NULL, error_code, error_cause);
744
                        goto jsondone;
745
                }
746
                json_t *plugin = json_object_get(root, "plugin");
747
                const gchar *plugin_text = json_string_value(plugin);
748
                janus_plugin *plugin_t = janus_plugin_find(plugin_text);
749
                if(plugin_t == NULL) {
750
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_NOT_FOUND, "No such plugin '%s'", plugin_text);
751
                        goto jsondone;
752
                }
753
                /* If the auth token mechanism is enabled, we should check if this token can access this plugin */
754
                if(janus_auth_is_enabled()) {
755
                        json_t *token = json_object_get(root, "token");
756
                        if(token != NULL) {
757
                                const char *token_value = json_string_value(token);
758
                                if(token_value && !janus_auth_check_plugin(token_value, plugin_t)) {
759
                                        JANUS_LOG(LOG_ERR, "Token '%s' can't access plugin '%s'\n", token_value, plugin_text);
760
                                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNAUTHORIZED_PLUGIN, "Provided token can't access plugin '%s'", plugin_text);
761
                                        goto jsondone;
762
                                }
763
                        }
764
                }
765
                /* Create handle */
766
                handle = janus_ice_handle_create(session);
767
                if(handle == NULL) {
768
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN, "Memory error");
769
                        goto jsondone;
770
                }
771
                handle_id = handle->handle_id;
772
                /* Attach to the plugin */
773
                int error = 0;
774
                if((error = janus_ice_handle_attach_plugin(session, handle_id, plugin_t)) != 0) {
775
                        /* TODO Make error struct to pass verbose information */
776
                        janus_ice_handle_destroy(session, handle_id);
777
                        janus_mutex_lock(&session->mutex);
778
                        g_hash_table_remove(session->ice_handles, GUINT_TO_POINTER(handle_id));
779
                        janus_mutex_unlock(&session->mutex);
780

    
781
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_ATTACH, "Couldn't attach to plugin: error '%d'", error);
782
                        goto jsondone;
783
                }
784
                /* Prepare JSON reply */
785
                json_t *reply = json_object();
786
                json_object_set_new(reply, "janus", json_string("success"));
787
                json_object_set_new(reply, "session_id", json_integer(session_id));
788
                json_object_set_new(reply, "transaction", json_string(transaction_text));
789
                json_t *data = json_object();
790
                json_object_set_new(data, "id", json_integer(handle_id));
791
                json_object_set_new(reply, "data", data);
792
                /* Send the success reply */
793
                ret = janus_process_success(request, reply);
794
        } else if(!strcasecmp(message_text, "destroy")) {
795
                if(handle != NULL) {
796
                        /* Query is a session-level command */
797
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
798
                        goto jsondone;
799
                }
800
                /* Schedule the session for deletion */
801
                session->destroy = 1;
802
                janus_mutex_lock(&sessions_mutex);
803
                g_hash_table_remove(sessions, GUINT_TO_POINTER(session->session_id));
804
                g_hash_table_insert(old_sessions, GUINT_TO_POINTER(session->session_id), session);
805
                GSource *timeout_source = g_timeout_source_new_seconds(3);
806
                g_source_set_callback(timeout_source, janus_cleanup_session, session, NULL);
807
                g_source_attach(timeout_source, sessions_watchdog_context);
808
                g_source_unref(timeout_source);
809
                janus_mutex_unlock(&sessions_mutex);
810
                /* Notify the source that the session has been destroyed */
811
                if(session->source && session->source->transport)
812
                        session->source->transport->session_over(session->source->instance, session->session_id, FALSE);
813

    
814
                /* Prepare JSON reply */
815
                json_t *reply = json_object();
816
                json_object_set_new(reply, "janus", json_string("success"));
817
                json_object_set_new(reply, "session_id", json_integer(session_id));
818
                json_object_set_new(reply, "transaction", json_string(transaction_text));
819
                /* Send the success reply */
820
                ret = janus_process_success(request, reply);
821
                /* Notify event handlers as well */
822
                if(janus_events_is_enabled())
823
                        janus_events_notify_handlers(JANUS_EVENT_TYPE_SESSION, session_id, "destroyed");
824
        } else if(!strcasecmp(message_text, "detach")) {
825
                if(handle == NULL) {
826
                        /* Query is an handle-level command */
827
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
828
                        goto jsondone;
829
                }
830
                if(handle->app == NULL || handle->app_handle == NULL) {
831
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_DETACH, "No plugin to detach from");
832
                        goto jsondone;
833
                }
834
                int error = janus_ice_handle_destroy(session, handle_id);
835
                janus_mutex_lock(&session->mutex);
836
                g_hash_table_remove(session->ice_handles, GUINT_TO_POINTER(handle_id));
837
                janus_mutex_unlock(&session->mutex);
838

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

    
1249
                /* Make sure the app handle is still valid */
1250
                if(handle->app == NULL || handle->app_handle == NULL || !janus_plugin_session_is_alive(handle->app_handle)) {
1251
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE, "No plugin to handle this message");
1252
                        if(jsep_type)
1253
                                g_free(jsep_type);
1254
                        if(jsep_sdp_stripped)
1255
                                g_free(jsep_sdp_stripped);
1256
                        janus_flags_clear(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER);
1257
                        goto jsondone;
1258
                }
1259

    
1260
                /* Send the message to the plugin (which must eventually free transaction_text, body_text, jsep_type and sdp) */
1261
                char *body_text = json_dumps(body, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
1262
                janus_plugin_result *result = plugin_t->handle_message(handle->app_handle, g_strdup((char *)transaction_text), body_text, jsep_type, jsep_sdp_stripped);
1263
                if(result == NULL) {
1264
                        /* Something went horribly wrong! */
1265
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE, "Plugin didn't give a result");
1266
                        goto jsondone;
1267
                }
1268
                if(result->type == JANUS_PLUGIN_OK) {
1269
                        /* The plugin gave a result already (synchronous request/response) */
1270
                        if(result->content == NULL) {
1271
                                /* Missing content... */
1272
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE, "Plugin didn't provide any content for this synchronous response");
1273
                                janus_plugin_result_destroy(result);
1274
                                goto jsondone;
1275
                        }
1276
                        json_error_t error;
1277
                        json_t *event = json_loads(result->content, 0, &error);
1278
                        if(!event) {
1279
                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Cannot send response from plugin (JSON error: on line %d: %s)\n", handle->handle_id, error.line, error.text);
1280
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE, "Plugin returned an invalid JSON response");
1281
                                janus_plugin_result_destroy(result);
1282
                                goto jsondone;
1283
                        }
1284
                        if(!json_is_object(event)) {
1285
                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Cannot send response from plugin (JSON error: not an object)\n", handle->handle_id);
1286
                                json_decref(event);
1287
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE, "Plugin returned an invalid JSON response");
1288
                                janus_plugin_result_destroy(result);
1289
                                goto jsondone;
1290
                        }
1291
                        /* Prepare JSON response */
1292
                        json_t *reply = json_object();
1293
                        json_object_set_new(reply, "janus", json_string("success"));
1294
                        json_object_set_new(reply, "session_id", json_integer(session->session_id));
1295
                        json_object_set_new(reply, "sender", json_integer(handle->handle_id));
1296
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1297
                        json_t *plugin_data = json_object();
1298
                        json_object_set_new(plugin_data, "plugin", json_string(plugin_t->get_package()));
1299
                        json_object_set_new(plugin_data, "data", event);
1300
                        json_object_set_new(reply, "plugindata", plugin_data);
1301
                        /* Send the success reply */
1302
                        ret = janus_process_success(request, reply);
1303
                } else if(result->type == JANUS_PLUGIN_OK_WAIT) {
1304
                        /* The plugin received the request but didn't process it yet, send an ack (asynchronous notifications may follow) */
1305
                        json_t *reply = json_object();
1306
                        json_object_set_new(reply, "janus", json_string("ack"));
1307
                        json_object_set_new(reply, "session_id", json_integer(session_id));
1308
                        if(result->content)
1309
                                json_object_set_new(reply, "hint", json_string(result->content));
1310
                        json_object_set_new(reply, "transaction", json_string(transaction_text));
1311
                        /* Send the success reply */
1312
                        ret = janus_process_success(request, reply);
1313
                } else {
1314
                        /* Something went horribly wrong! */
1315
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE, "%s", result->content ? g_strdup(result->content) : "Plugin returned a severe (unknown) error");
1316
                        janus_plugin_result_destroy(result);
1317
                        goto jsondone;
1318
                }                        
1319
                janus_plugin_result_destroy(result);
1320
        } else if(!strcasecmp(message_text, "trickle")) {
1321
                if(handle == NULL) {
1322
                        /* Trickle is an handle-level command */
1323
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_REQUEST_PATH, "Unhandled request '%s' at this path", message_text);
1324
                        goto jsondone;
1325
                }
1326
                if(handle->app == NULL || handle->app_handle == NULL || !janus_plugin_session_is_alive(handle->app_handle)) {
1327
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_PLUGIN_MESSAGE, "No plugin to handle this trickle candidate");
1328
                        goto jsondone;
1329
                }
1330
                json_t *candidate = json_object_get(root, "candidate");
1331
                json_t *candidates = json_object_get(root, "candidates");
1332
                if(candidate == NULL && candidates == NULL) {
1333
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_MISSING_MANDATORY_ELEMENT, "Missing mandatory element (candidate|candidates)");
1334
                        goto jsondone;
1335
                }
1336
                if(candidate != NULL && candidates != NULL) {
1337
                        ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_JSON, "Can't have both candidate and candidates");
1338
                        goto jsondone;
1339
                }
1340
                janus_mutex_lock(&handle->mutex);
1341
                if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_TRICKLE)) {
1342
                        /* It looks like this peer supports Trickle, after all */
1343
                        JANUS_LOG(LOG_VERB, "Handle %"SCNu64" supports trickle even if it didn't negotiate it...\n", handle->handle_id);
1344
                        janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_TRICKLE);
1345
                }
1346
                /* Is there any stream ready? this trickle may get here before the SDP it relates to */
1347
                if(handle->audio_stream == NULL && handle->video_stream == NULL && handle->data_stream == NULL) {
1348
                        JANUS_LOG(LOG_WARN, "[%"SCNu64"] No stream, queueing this trickle as it got here before the SDP...\n", handle->handle_id);
1349
                        /* Enqueue this trickle candidate(s), we'll process this later */
1350
                        janus_ice_trickle *early_trickle = janus_ice_trickle_new(handle, transaction_text, candidate ? candidate : candidates);
1351
                        handle->pending_trickles = g_list_append(handle->pending_trickles, early_trickle);
1352
                        /* Send the ack right away, an event will tell the application if the candidate(s) failed */
1353
                        goto trickledone;
1354
                }
1355
                /* Is the ICE stack ready already? */
1356
                if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER) ||
1357
                                !janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_OFFER) ||
1358
                                !janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_ANSWER)) {
1359
                        const char *cause = NULL;
1360
                        if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_PROCESSING_OFFER))
1361
                                cause = "processing the offer";
1362
                        else if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_ANSWER))
1363
                                cause = "waiting for the answer";
1364
                        else if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_GOT_OFFER))
1365
                                cause = "waiting for the offer";
1366
                        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Still %s, queueing this trickle to wait until we're done there...\n",
1367
                                handle->handle_id, cause);
1368
                        /* Enqueue this trickle candidate(s), we'll process this later */
1369
                        janus_ice_trickle *early_trickle = janus_ice_trickle_new(handle, transaction_text, candidate ? candidate : candidates);
1370
                        handle->pending_trickles = g_list_append(handle->pending_trickles, early_trickle);
1371
                        /* Send the ack right away, an event will tell the application if the candidate(s) failed */
1372
                        goto trickledone;
1373
                }
1374
                if(candidate != NULL) {
1375
                        /* We got a single candidate */
1376
                        int error = 0;
1377
                        const char *error_string = NULL;
1378
                        if((error = janus_ice_trickle_parse(handle, candidate, &error_string)) != 0) {
1379
                                ret = janus_process_error(request, session_id, transaction_text, error, "%s", error_string);
1380
                                janus_mutex_unlock(&handle->mutex);
1381
                                goto jsondone;
1382
                        }
1383
                } else {
1384
                        /* We got multiple candidates in an array */
1385
                        if(!json_is_array(candidates)) {
1386
                                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_INVALID_ELEMENT_TYPE, "candidates is not an array");
1387
                                janus_mutex_unlock(&handle->mutex);
1388
                                goto jsondone;
1389
                        }
1390
                        JANUS_LOG(LOG_VERB, "Got multiple candidates (%zu)\n", json_array_size(candidates));
1391
                        if(json_array_size(candidates) > 0) {
1392
                                /* Handle remote candidates */
1393
                                size_t i = 0;
1394
                                for(i=0; i<json_array_size(candidates); i++) {
1395
                                        json_t *c = json_array_get(candidates, i);
1396
                                        /* FIXME We don't care if any trickle fails to parse */
1397
                                        janus_ice_trickle_parse(handle, c, NULL);
1398
                                }
1399
                        }
1400
                }
1401

    
1402
trickledone:
1403
                janus_mutex_unlock(&handle->mutex);
1404
                /* We reply right away, not to block the web server... */
1405
                json_t *reply = json_object();
1406
                json_object_set_new(reply, "janus", json_string("ack"));
1407
                json_object_set_new(reply, "session_id", json_integer(session_id));
1408
                json_object_set_new(reply, "transaction", json_string(transaction_text));
1409
                /* Send the success reply */
1410
                ret = janus_process_success(request, reply);
1411
        } else {
1412
                ret = janus_process_error(request, session_id, transaction_text, JANUS_ERROR_UNKNOWN_REQUEST, "Unknown request '%s'", message_text);
1413
        }
1414

    
1415
jsondone:
1416
        /* Done processing */
1417
        return ret;
1418
}
1419

    
1420
/* Admin/monitor WebServer requests handler */
1421
int janus_process_incoming_admin_request(janus_request *request) {
1422
        int ret = -1;
1423
        if(request == NULL) {
1424
                JANUS_LOG(LOG_ERR, "Missing request or payload to process, giving up...\n");
1425
                return ret;
1426
        }
1427
        json_t *root = request->message;
1428
        /* Ok, let's start with the ids */
1429
        guint64 session_id = 0, handle_id = 0;
1430
        json_t *s = json_object_get(root, "session_id");
1431
        if(s && json_is_integer(s))
1432
                session_id = json_integer_value(s);
1433
        json_t *h = json_object_get(root, "handle_id");
1434
        if(h && json_is_integer(h))
1435
                handle_id = json_integer_value(h);
1436

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

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

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

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

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

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

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

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

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

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

    
2399

    
2400
/* Transports */
2401
void janus_transport_close(gpointer key, gpointer value, gpointer user_data) {
2402
        janus_transport *transport = (janus_transport *)value;
2403
        if(!transport)
2404
                return;
2405
        transport->destroy();
2406
}
2407

    
2408
void janus_transportso_close(gpointer key, gpointer value, gpointer user_data) {
2409
        void *transport = (janus_transport *)value;
2410
        if(!transport)
2411
                return;
2412
        //~ dlclose(transport);
2413
}
2414

    
2415
/* Transport callback interface */
2416
void janus_transport_incoming_request(janus_transport *plugin, void *transport, void *request_id, gboolean admin, json_t *message, json_error_t *error) {
2417
        JANUS_LOG(LOG_VERB, "Got %s API request from %s (%p)\n", admin ? "an admin" : "a Janus", plugin->get_package(), transport);
2418
        /* Create a janus_request instance to handle the request */
2419
        janus_request *request = janus_request_new(plugin, transport, request_id, admin, message);
2420
        GError *tperror = NULL;
2421
        g_thread_pool_push(tasks, request, &tperror);
2422
        if(tperror != NULL) {
2423
                /* Something went wrong... */
2424
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to push task in thread pool...\n", tperror->code, tperror->message ? tperror->message : "??");
2425
                json_t *transaction = json_object_get(message, "transaction");
2426
                const char *transaction_text = json_is_string(transaction) ? json_string_value(transaction) : NULL;
2427
                janus_process_error(request, 0, transaction_text, JANUS_ERROR_UNKNOWN, "Thread pool error");
2428
                janus_request_destroy(request);
2429
        }
2430
}
2431

    
2432
void janus_transport_gone(janus_transport *plugin, void *transport) {
2433
        /* Get rid of sessions this transport was handling */
2434
        JANUS_LOG(LOG_VERB, "A %s transport instance has gone away (%p)\n", plugin->get_package(), transport);
2435
        janus_mutex_lock(&sessions_mutex);
2436
        if(sessions && g_hash_table_size(sessions) > 0) {
2437
                GHashTableIter iter;
2438
                gpointer value;
2439
                g_hash_table_iter_init(&iter, sessions);
2440
                while(g_hash_table_iter_next(&iter, NULL, &value)) {
2441
                        janus_session *session = (janus_session *) value;
2442
                        if(!session || session->destroy || session->timeout || session->last_activity == 0)
2443
                                continue;
2444
                        if(session->source && session->source->instance == transport) {
2445
                                JANUS_LOG(LOG_VERB, "  -- Marking Session %"SCNu64" as over\n", session->session_id);
2446
                                session->last_activity = 0;        /* This will trigger a timeout */
2447
                        }
2448
                }
2449
        }
2450
        janus_mutex_unlock(&sessions_mutex);
2451
}
2452

    
2453
gboolean janus_transport_is_api_secret_needed(janus_transport *plugin) {
2454
        return api_secret != NULL;
2455
}
2456

    
2457
gboolean janus_transport_is_api_secret_valid(janus_transport *plugin, const char *apisecret) {
2458
        if(api_secret == NULL)
2459
                return TRUE;
2460
        return apisecret && janus_strcmp_const_time(apisecret, api_secret);
2461
}
2462

    
2463
gboolean janus_transport_is_auth_token_needed(janus_transport *plugin) {
2464
        return janus_auth_is_enabled();
2465
}
2466

    
2467
gboolean janus_transport_is_auth_token_valid(janus_transport *plugin, const char *token) {
2468
        if(!janus_auth_is_enabled())
2469
                return TRUE;
2470
        return token && janus_auth_check_token(token);
2471
}
2472

    
2473
void janus_transport_task(gpointer data, gpointer user_data) {
2474
        JANUS_LOG(LOG_VERB, "Transport task pool, serving request\n");
2475
        janus_request *request = (janus_request *)data;
2476
        if(request == NULL) {
2477
                JANUS_LOG(LOG_ERR, "Missing request\n");
2478
                return;
2479
        }
2480
        if(!request->admin)
2481
                janus_process_incoming_request(request);
2482
        else
2483
                janus_process_incoming_admin_request(request);
2484
        /* Done */
2485
        janus_request_destroy(request);
2486
}
2487

    
2488

    
2489
/* Event handlers */
2490
void janus_eventhandler_close(gpointer key, gpointer value, gpointer user_data) {
2491
        janus_eventhandler *eventhandler = (janus_eventhandler *)value;
2492
        if(!eventhandler)
2493
                return;
2494
        eventhandler->destroy();
2495
}
2496

    
2497
void janus_eventhandlerso_close(gpointer key, gpointer value, gpointer user_data) {
2498
        void *eventhandler = (janus_eventhandler *)value;
2499
        if(!eventhandler)
2500
                return;
2501
        //~ dlclose(eventhandler);
2502
}
2503

    
2504

    
2505
/* Plugins */
2506
void janus_plugin_close(gpointer key, gpointer value, gpointer user_data) {
2507
        janus_plugin *plugin = (janus_plugin *)value;
2508
        if(!plugin)
2509
                return;
2510
        plugin->destroy();
2511
}
2512

    
2513
void janus_pluginso_close(gpointer key, gpointer value, gpointer user_data) {
2514
        void *plugin = (janus_plugin *)value;
2515
        if(!plugin)
2516
                return;
2517
        //~ dlclose(plugin);
2518
}
2519

    
2520
janus_plugin *janus_plugin_find(const gchar *package) {
2521
        if(package != NULL && plugins != NULL)        /* FIXME Do we need to fix the key pointer? */
2522
                return g_hash_table_lookup(plugins, package);
2523
        return NULL;
2524
}
2525

    
2526

    
2527
/* Plugin callback interface */
2528
int janus_plugin_push_event(janus_plugin_session *plugin_session, janus_plugin *plugin, const char *transaction, const char *message, const char *sdp_type, const char *sdp) {
2529
        if(!plugin || !message)
2530
                return -1;
2531
        if(!plugin_session || plugin_session < (janus_plugin_session *)0x1000 ||
2532
                        !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped)
2533
                return -2;
2534
        janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
2535
        if(!ice_handle || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP))
2536
                return JANUS_ERROR_SESSION_NOT_FOUND;
2537
        janus_session *session = ice_handle->session;
2538
        if(!session || session->destroy)
2539
                return JANUS_ERROR_SESSION_NOT_FOUND;
2540
        /* Make sure this is JSON */
2541
        json_error_t error;
2542
        json_t *plugin_event = json_loads(message, 0, &error);
2543
        if(!plugin_event) {
2544
                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Cannot push event (JSON error: on line %d: %s)\n", ice_handle->handle_id, error.line, error.text);
2545
                return JANUS_ERROR_INVALID_JSON;
2546
        }
2547
        if(!json_is_object(plugin_event)) {
2548
                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Cannot push event (JSON error: not an object)\n", ice_handle->handle_id);
2549
                return JANUS_ERROR_INVALID_JSON_OBJECT;
2550
        }
2551
        /* Attach JSEP if possible? */
2552
        json_t *jsep = NULL;
2553
        if(sdp_type != NULL && sdp != NULL) {
2554
                jsep = janus_plugin_handle_sdp(plugin_session, plugin, sdp_type, sdp);
2555
                if(jsep == NULL) {
2556
                        if(ice_handle == NULL || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
2557
                                        || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT)) {
2558
                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Cannot push event (handle not available anymore or negotiation stopped)\n", ice_handle->handle_id);
2559
                                return JANUS_ERROR_HANDLE_NOT_FOUND;
2560
                        } else {
2561
                                JANUS_LOG(LOG_ERR, "[%"SCNu64"] Cannot push event (JSON error: problem with the SDP)\n", ice_handle->handle_id);
2562
                                return JANUS_ERROR_JSEP_INVALID_SDP;
2563
                        }
2564
                }
2565
        }
2566
        /* Prepare JSON event */
2567
        json_t *event = json_object();
2568
        json_object_set_new(event, "janus", json_string("event"));
2569
        json_object_set_new(event, "session_id", json_integer(session->session_id));
2570
        json_object_set_new(event, "sender", json_integer(ice_handle->handle_id));
2571
        if(transaction != NULL)
2572
                json_object_set_new(event, "transaction", json_string(transaction));
2573
        json_t *plugin_data = json_object();
2574
        json_object_set_new(plugin_data, "plugin", json_string(plugin->get_package()));
2575
        json_object_set_new(plugin_data, "data", plugin_event);
2576
        json_object_set_new(event, "plugindata", plugin_data);
2577
        if(jsep != NULL)
2578
                json_object_set_new(event, "jsep", jsep);
2579
        /* Send the event */
2580
        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Sending event to transport...\n", ice_handle->handle_id);
2581
        janus_session_notify_event(session->session_id, event);
2582

    
2583
        if(jsep != NULL && janus_events_is_enabled()) {
2584
                /* Notify event handlers as well */
2585
                janus_events_notify_handlers(JANUS_EVENT_TYPE_JSEP,
2586
                        session->session_id, ice_handle->handle_id, "local", sdp_type, sdp);
2587
        }
2588

    
2589
        return JANUS_OK;
2590
}
2591

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

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

    
2920
void janus_plugin_relay_rtp(janus_plugin_session *plugin_session, int video, char *buf, int len) {
2921
        if((plugin_session < (janus_plugin_session *)0x1000) || plugin_session->stopped || buf == NULL || len < 1)
2922
                return;
2923
        janus_ice_handle *handle = (janus_ice_handle *)plugin_session->gateway_handle;
2924
        if(!handle || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
2925
                        || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
2926
                return;
2927
        janus_ice_relay_rtp(handle, video, buf, len);
2928
}
2929

    
2930
void janus_plugin_relay_rtcp(janus_plugin_session *plugin_session, int video, char *buf, int len) {
2931
        if((plugin_session < (janus_plugin_session *)0x1000) || plugin_session->stopped || buf == NULL || len < 1)
2932
                return;
2933
        janus_ice_handle *handle = (janus_ice_handle *)plugin_session->gateway_handle;
2934
        if(!handle || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
2935
                        || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
2936
                return;
2937
        janus_ice_relay_rtcp(handle, video, buf, len);
2938
}
2939

    
2940
void janus_plugin_relay_data(janus_plugin_session *plugin_session, char *buf, int len) {
2941
        if((plugin_session < (janus_plugin_session *)0x1000) || plugin_session->stopped || buf == NULL || len < 1)
2942
                return;
2943
        janus_ice_handle *handle = (janus_ice_handle *)plugin_session->gateway_handle;
2944
        if(!handle || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
2945
                        || janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
2946
                return;
2947
#ifdef HAVE_SCTP
2948
        janus_ice_relay_data(handle, buf, len);
2949
#else
2950
        JANUS_LOG(LOG_WARN, "Asked to relay data, but Data Channels support has not been compiled...\n");
2951
#endif
2952
}
2953

    
2954
void janus_plugin_close_pc(janus_plugin_session *plugin_session) {
2955
        /* A plugin asked to get rid of a PeerConnection */
2956
        if((plugin_session < (janus_plugin_session *)0x1000) || !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped)
2957
                return;
2958
        janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
2959
        if(!ice_handle)
2960
                return;
2961
        if(janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP)
2962
                        || janus_flags_is_set(&ice_handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
2963
                return;
2964
        janus_session *session = (janus_session *)ice_handle->session;
2965
        if(!session)
2966
                return;
2967
                
2968
        JANUS_LOG(LOG_VERB, "[%"SCNu64"] Plugin asked to hangup PeerConnection: sending alert\n", ice_handle->handle_id);
2969
        /* Send an alert on all the DTLS connections */
2970
        janus_ice_webrtc_hangup(ice_handle);
2971
}
2972

    
2973
void janus_plugin_end_session(janus_plugin_session *plugin_session) {
2974
        /* A plugin asked to get rid of a handle */
2975
        if((plugin_session < (janus_plugin_session *)0x1000) || !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped)
2976
                return;
2977
        janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
2978
        if(!ice_handle)
2979
                return;
2980
        janus_session *session = (janus_session *)ice_handle->session;
2981
        if(!session)
2982
                return;
2983
        /* Destroy the handle */
2984
        janus_ice_handle_destroy(session, ice_handle->handle_id);
2985
        janus_mutex_lock(&session->mutex);
2986
        g_hash_table_remove(session->ice_handles, GUINT_TO_POINTER(ice_handle->handle_id));
2987
        janus_mutex_unlock(&session->mutex);
2988
}
2989

    
2990
void janus_plugin_notify_event(janus_plugin_session *plugin_session, json_t *event) {
2991
        /* A plugin asked to notify an event to the handlers */
2992
        if(!event || !json_is_object(event))
2993
                return;
2994
        if((plugin_session < (janus_plugin_session *)0x1000) || !janus_plugin_session_is_alive(plugin_session) || plugin_session->stopped) {
2995
                json_decref(event);
2996
                return;
2997
        }
2998
        janus_ice_handle *ice_handle = (janus_ice_handle *)plugin_session->gateway_handle;
2999
        if(!ice_handle) {
3000
                json_decref(event);
3001
                return;
3002
        }
3003
        janus_session *session = (janus_session *)ice_handle->session;
3004
        if(!session) {
3005
                json_decref(event);
3006
                return;
3007
        }
3008
        janus_plugin *plugin_t = (janus_plugin *)ice_handle->app;
3009
        /* Notify event handlers */
3010
        if(janus_events_is_enabled()) {
3011
                janus_events_notify_handlers(JANUS_EVENT_TYPE_PLUGIN,
3012
                        session->session_id, ice_handle->handle_id, plugin_t->get_package(), event);
3013
        } else {
3014
                json_decref(event);
3015
        }
3016
}
3017

    
3018

    
3019
static void janus_detect_local_ip(gchar *buf, size_t buflen) {
3020
        JANUS_LOG(LOG_VERB, "Autodetecting local IP...\n");
3021
        struct sockaddr_in addr;
3022
        socklen_t len;
3023
        int fd = socket(AF_INET, SOCK_DGRAM, 0);
3024
        if (fd == -1)
3025
                goto error;
3026
        addr.sin_family = AF_INET;
3027
        addr.sin_port = htons(1);
3028
        inet_pton(AF_INET, "1.2.3.4", &addr.sin_addr.s_addr);
3029
        if (connect(fd, (const struct sockaddr*) &addr, sizeof(addr)) < 0)
3030
                goto error;
3031
        len = sizeof(addr);
3032
        if (getsockname(fd, (struct sockaddr*) &addr, &len) < 0)
3033
                goto error;
3034
        if (getnameinfo((const struct sockaddr*) &addr, sizeof(addr),
3035
                        buf, buflen,
3036
                        NULL, 0, NI_NUMERICHOST) != 0)
3037
                goto error;
3038
        close(fd);
3039
        return;
3040
error:
3041
        if (fd != -1)
3042
                close(fd);
3043
        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");
3044
        g_strlcpy(buf, "127.0.0.1", buflen);
3045
}
3046

    
3047

    
3048
/* Main */
3049
gint main(int argc, char *argv[])
3050
{
3051
        /* Core dumps may be disallowed by parent of this process; change that */
3052
        struct rlimit core_limits;
3053
        core_limits.rlim_cur = core_limits.rlim_max = RLIM_INFINITY;
3054
        setrlimit(RLIMIT_CORE, &core_limits);
3055

    
3056
        struct gengetopt_args_info args_info;
3057
        /* Let's call our cmdline parser */
3058
        if(cmdline_parser(argc, argv, &args_info) != 0)
3059
                exit(1);
3060
        
3061
        /* Any configuration to open? */
3062
        if(args_info.config_given) {
3063
                config_file = g_strdup(args_info.config_arg);
3064
        }
3065
        if(args_info.configs_folder_given) {
3066
                configs_folder = g_strdup(args_info.configs_folder_arg);
3067
        } else {
3068
                configs_folder = g_strdup (CONFDIR);
3069
        }
3070
        if(config_file == NULL) {
3071
                char file[255];
3072
                g_snprintf(file, 255, "%s/janus.cfg", configs_folder);
3073
                config_file = g_strdup(file);
3074
        }
3075
        if((config = janus_config_parse(config_file)) == NULL) {
3076
                if(args_info.config_given) {
3077
                        /* We only give up if the configuration file was explicitly provided */
3078
                        g_print("Error reading configuration from %s\n", config_file);
3079
                        exit(1);
3080
                }
3081
                g_print("Error reading/parsing the configuration file, going on with the defaults and the command line arguments\n");
3082
                config = janus_config_create("janus.cfg");
3083
                if(config == NULL) {
3084
                        /* If we can't even create an empty configuration, something's definitely wrong */
3085
                        exit(1);
3086
                }
3087
        }
3088

    
3089
        /* Check if we need to log to console and/or file */
3090
        gboolean use_stdout = TRUE;
3091
        if(args_info.disable_stdout_given) {
3092
                use_stdout = FALSE;
3093
                janus_config_add_item(config, "general", "log_to_stdout", "no");
3094
        } else {
3095
                /* Check if the configuration file is saying anything about this */
3096
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "log_to_stdout");
3097
                if(item && item->value && !janus_is_true(item->value))
3098
                        use_stdout = FALSE;
3099
        }
3100
        const char *logfile = NULL;
3101
        if(args_info.log_file_given) {
3102
                logfile = args_info.log_file_arg;
3103
                janus_config_add_item(config, "general", "log_to_file", "no");
3104
        } else {
3105
                /* Check if the configuration file is saying anything about this */
3106
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "log_to_file");
3107
                if(item && item->value)
3108
                        logfile = item->value;
3109
        }
3110

    
3111
        /* Check if we're going to daemonize Janus */
3112
        if(args_info.daemon_given) {
3113
                daemonize = TRUE;
3114
                janus_config_add_item(config, "general", "daemonize", "yes");
3115
        } else {
3116
                /* Check if the configuration file is saying anything about this */
3117
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "daemonize");
3118
                if(item && item->value && janus_is_true(item->value))
3119
                        daemonize = TRUE;
3120
        }
3121
        /* If we're going to daemonize, make sure logging to stdout is disabled and a log file has been specified */
3122
        if(daemonize && use_stdout) {
3123
                use_stdout = FALSE;
3124
        }
3125
        if(daemonize && logfile == NULL) {
3126
                g_print("Running Janus as a daemon but no log file provided, giving up...\n");
3127
                exit(1);
3128
        }
3129
        /* Daemonize now, if we need to */
3130
        if(daemonize) {
3131
                g_print("Running Janus as a daemon\n");
3132

    
3133
                /* Create a pipe for parent<->child communication during the startup phase */
3134
                if(pipe(pipefd) == -1) {
3135
                        g_print("pipe error!\n");
3136
                        exit(1);
3137
                }
3138

    
3139
                /* Fork off the parent process */
3140
                pid_t pid = fork();
3141
                if(pid < 0) {
3142
                        g_print("Fork error!\n");
3143
                        exit(1);
3144
                }
3145
                if(pid > 0) {
3146
                        /* Ok, we're the parent: let's wait for the child to tell us everything started fine */
3147
                        close(pipefd[1]);
3148
                        int code = -1;
3149
                        struct pollfd pollfds;
3150

    
3151
                        while(code < 0) {
3152
                                pollfds.fd = pipefd[0];
3153
                                pollfds.events = POLLIN;
3154
                                int res = poll(&pollfds, 1, -1);
3155
                                if(res < 0)
3156
                                        break;
3157
                                if(res == 0)
3158
                                        continue;
3159
                                if(pollfds.revents & POLLERR || pollfds.revents & POLLHUP)
3160
                                        break;
3161
                                if(pollfds.revents & POLLIN) {
3162
                                        read(pipefd[0], &code, sizeof(int));
3163
                                        break;
3164
                                }
3165
                        }
3166
                        if(code < 0)
3167
                                code = 1;
3168

    
3169
                        /* Leave the parent and return the exit code we received from the child */
3170
                        if(code)
3171
                                g_print("Error launching Janus (error code %d), check the logs for more details\n", code);
3172
                        exit(code);
3173
                }
3174
                /* Change the file mode mask */
3175
                umask(0);
3176

    
3177
                /* Create a new SID for the child process */
3178
                pid_t sid = setsid();
3179
                if(sid < 0) {
3180
                        g_print("Error setting SID!\n");
3181
                        exit(1);
3182
                }
3183
                /* Change the current working directory */
3184
                if((chdir("/")) < 0) {
3185
                        g_print("Error changing the current working directory!\n");
3186
                        exit(1);
3187
                }
3188
                /* We close stdin/stdout/stderr when initializing the logger */
3189
        }
3190

    
3191
        /* Initialize logger */
3192
        if(janus_log_init(daemonize, use_stdout, logfile) < 0)
3193
                exit(1);
3194

    
3195
        JANUS_PRINT("---------------------------------------------------\n");
3196
        JANUS_PRINT("  Starting Meetecho Janus (WebRTC Gateway) v%s\n", JANUS_VERSION_STRING);
3197
        JANUS_PRINT("---------------------------------------------------\n\n");
3198

    
3199
        /* Handle SIGINT (CTRL-C), SIGTERM (from service managers) */
3200
        signal(SIGINT, janus_handle_signal);
3201
        signal(SIGTERM, janus_handle_signal);
3202
        atexit(janus_termination_handler);
3203

    
3204
        /* Setup Glib */
3205
#if !GLIB_CHECK_VERSION(2, 36, 0)
3206
        g_type_init();
3207
#endif
3208

    
3209
        /* Logging level: default is info and no timestamps */
3210
        janus_log_level = LOG_INFO;
3211
        janus_log_timestamps = FALSE;
3212
        janus_log_colors = TRUE;
3213
        if(args_info.debug_level_given) {
3214
                if(args_info.debug_level_arg < LOG_NONE)
3215
                        args_info.debug_level_arg = 0;
3216
                else if(args_info.debug_level_arg > LOG_MAX)
3217
                        args_info.debug_level_arg = LOG_MAX;
3218
                janus_log_level = args_info.debug_level_arg;
3219
        }
3220

    
3221
        /* Any PID we need to create? */
3222
        const char *pidfile = NULL;
3223
        if(args_info.pid_file_given) {
3224
                pidfile = args_info.pid_file_arg;
3225
                janus_config_add_item(config, "general", "pid_file", pidfile);
3226
        } else {
3227
                /* Check if the configuration file is saying anything about this */
3228
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "pid_file");
3229
                if(item && item->value)
3230
                        pidfile = item->value;
3231
        }
3232
        if(janus_pidfile_create(pidfile) < 0)
3233
                exit(1);
3234

    
3235
        /* Proceed with the rest of the configuration */
3236
        janus_config_print(config);
3237
        if(args_info.debug_level_given) {
3238
                char debug[5];
3239
                g_snprintf(debug, 5, "%d", args_info.debug_level_arg);
3240
                janus_config_add_item(config, "general", "debug_level", debug);
3241
        } else {
3242
                /* No command line directive on logging, try the configuration file */
3243
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "debug_level");
3244
                if(item && item->value) {
3245
                        int temp_level = atoi(item->value);
3246
                        if(temp_level == 0 && strcmp(item->value, "0")) {
3247
                                JANUS_PRINT("Invalid debug level %s (configuration), using default (info=4)\n", item->value);
3248
                        } else {
3249
                                janus_log_level = temp_level;
3250
                                if(janus_log_level < LOG_NONE)
3251
                                        janus_log_level = 0;
3252
                                else if(janus_log_level > LOG_MAX)
3253
                                        janus_log_level = LOG_MAX;
3254
                        }
3255
                }
3256
        }
3257
        /* Any command line argument that should overwrite the configuration? */
3258
        JANUS_PRINT("Checking command line arguments...\n");
3259
        if(args_info.debug_timestamps_given) {
3260
                janus_config_add_item(config, "general", "debug_timestamps", "yes");
3261
        }
3262
        if(args_info.disable_colors_given) {
3263
                janus_config_add_item(config, "general", "debug_colors", "no");
3264
        }
3265
        if(args_info.server_name_given) {
3266
                janus_config_add_item(config, "general", "server_name", args_info.server_name_arg);
3267
        }
3268
         if(args_info.interface_given) {
3269
                janus_config_add_item(config, "general", "interface", args_info.interface_arg);
3270
        }
3271
        if(args_info.configs_folder_given) {
3272
                janus_config_add_item(config, "general", "configs_folder", args_info.configs_folder_arg);
3273
        }
3274
        if(args_info.plugins_folder_given) {
3275
                janus_config_add_item(config, "general", "plugins_folder", args_info.plugins_folder_arg);
3276
        }
3277
        if(args_info.apisecret_given) {
3278
                janus_config_add_item(config, "general", "api_secret", args_info.apisecret_arg);
3279
        }
3280
        if(args_info.token_auth_given) {
3281
                janus_config_add_item(config, "general", "token_auth", "yes");
3282
        }
3283
        if(args_info.cert_pem_given) {
3284
                janus_config_add_item(config, "certificates", "cert_pem", args_info.cert_pem_arg);
3285
        }
3286
        if(args_info.cert_key_given) {
3287
                janus_config_add_item(config, "certificates", "cert_key", args_info.cert_key_arg);
3288
        }
3289
        if(args_info.stun_server_given) {
3290
                /* Split in server and port (if port missing, use 3478 as default) */
3291
                char *stunport = strrchr(args_info.stun_server_arg, ':');
3292
                if(stunport != NULL) {
3293
                        *stunport = '\0';
3294
                        stunport++;
3295
                        janus_config_add_item(config, "nat", "stun_server", args_info.stun_server_arg);
3296
                        janus_config_add_item(config, "nat", "stun_port", stunport);
3297
                } else {
3298
                        janus_config_add_item(config, "nat", "stun_server", args_info.stun_server_arg);
3299
                        janus_config_add_item(config, "nat", "stun_port", "3478");
3300
                }
3301
        }
3302
        if(args_info.nat_1_1_given) {
3303
                janus_config_add_item(config, "nat", "nat_1_1_mapping", args_info.nat_1_1_arg);
3304
        }
3305
        if(args_info.ice_enforce_list_given) {
3306
                janus_config_add_item(config, "nat", "ice_enforce_list", args_info.ice_enforce_list_arg);
3307
        }
3308
        if(args_info.ice_ignore_list_given) {
3309
                janus_config_add_item(config, "nat", "ice_ignore_list", args_info.ice_ignore_list_arg);
3310
        }
3311
        if(args_info.libnice_debug_given) {
3312
                janus_config_add_item(config, "nat", "nice_debug", "true");
3313
        }
3314
        if(args_info.ice_lite_given) {
3315
                janus_config_add_item(config, "nat", "ice_lite", "true");
3316
        }
3317
        if(args_info.ice_tcp_given) {
3318
                janus_config_add_item(config, "nat", "ice_tcp", "true");
3319
        }
3320
        if(args_info.ipv6_candidates_given) {
3321
                janus_config_add_item(config, "media", "ipv6", "true");
3322
        }
3323
        if(args_info.force_bundle_given) {
3324
                janus_config_add_item(config, "media", "force-bundle", "true");
3325
        }
3326
        if(args_info.force_rtcp_mux_given) {
3327
                janus_config_add_item(config, "media", "force-rtcp-mux", "true");
3328
        }
3329
        if(args_info.max_nack_queue_given) {
3330
                char mnq[20];
3331
                g_snprintf(mnq, 20, "%d", args_info.max_nack_queue_arg);
3332
                janus_config_add_item(config, "media", "max_nack_queue", mnq);
3333
        }
3334
        if(args_info.rtp_port_range_given) {
3335
                janus_config_add_item(config, "media", "rtp_port_range", args_info.rtp_port_range_arg);
3336
        }
3337
        janus_config_print(config);
3338

    
3339
        /* Logging/debugging */
3340
        JANUS_PRINT("Debug/log level is %d\n", janus_log_level);
3341
        janus_config_item *item = janus_config_get_item_drilldown(config, "general", "debug_timestamps");
3342
        if(item && item->value)
3343
                janus_log_timestamps = janus_is_true(item->value);
3344
        JANUS_PRINT("Debug/log timestamps are %s\n", janus_log_timestamps ? "enabled" : "disabled");
3345
        item = janus_config_get_item_drilldown(config, "general", "debug_colors");
3346
        if(item && item->value)
3347
                janus_log_colors = janus_is_true(item->value);
3348
        JANUS_PRINT("Debug/log colors are %s\n", janus_log_colors ? "enabled" : "disabled");
3349

    
3350
        /* Any IP/interface to enforce/ignore? */
3351
        item = janus_config_get_item_drilldown(config, "nat", "ice_enforce_list");
3352
        if(item && item->value) {
3353
                gchar **list = g_strsplit(item->value, ",", -1);
3354
                gchar *index = list[0];
3355
                if(index != NULL) {
3356
                        int i=0;
3357
                        while(index != NULL) {
3358
                                if(strlen(index) > 0) {
3359
                                        JANUS_LOG(LOG_INFO, "Adding '%s' to the ICE enforce list...\n", index);
3360
                                        janus_ice_enforce_interface(g_strdup(index));
3361
                                }
3362
                                i++;
3363
                                index = list[i];
3364
                        }
3365
                }
3366
                g_strfreev(list);
3367
                list = NULL;
3368
        }
3369
        item = janus_config_get_item_drilldown(config, "nat", "ice_ignore_list");
3370
        if(item && item->value) {
3371
                gchar **list = g_strsplit(item->value, ",", -1);
3372
                gchar *index = list[0];
3373
                if(index != NULL) {
3374
                        int i=0;
3375
                        while(index != NULL) {
3376
                                if(strlen(index) > 0) {
3377
                                        JANUS_LOG(LOG_INFO, "Adding '%s' to the ICE ignore list...\n", index);
3378
                                        janus_ice_ignore_interface(g_strdup(index));
3379
                                }
3380
                                i++;
3381
                                index = list[i];
3382
                        }
3383
                }
3384
                g_strfreev(list);
3385
                list = NULL;
3386
        }
3387
        /* What is the local IP? */
3388
        JANUS_LOG(LOG_VERB, "Selecting local IP address...\n");
3389
        gboolean local_ip_set = FALSE;
3390
        item = janus_config_get_item_drilldown(config, "general", "interface");
3391
        if(item && item->value) {
3392
                JANUS_LOG(LOG_VERB, "  -- Will try to use %s\n", item->value);
3393
                int family;
3394
                if (!janus_is_ip_valid(item->value, &family)) {
3395
                        JANUS_LOG(LOG_WARN, "Invalid local IP specified: %s, guessing the default...\n", item->value);
3396
                } else {
3397
                        /* Verify that we can actually bind to that address */
3398
                        int fd = socket(family, SOCK_DGRAM, 0);
3399
                        if (fd == -1) {
3400
                                JANUS_LOG(LOG_WARN, "Error creating test socket, falling back to detecting IP address...\n");
3401
                        } else {
3402
                                int r;
3403
                                struct sockaddr_storage ss;
3404
                                socklen_t addrlen;
3405
                                memset(&ss, 0, sizeof(ss));
3406
                                if (family == AF_INET) {
3407
                                        struct sockaddr_in *addr4 = (struct sockaddr_in*)&ss;
3408
                                        addr4->sin_family = AF_INET;
3409
                                        addr4->sin_port = 0;
3410
                                        inet_pton(AF_INET, item->value, &(addr4->sin_addr.s_addr));
3411
                                        addrlen = sizeof(struct sockaddr_in);
3412
                                } else {
3413
                                        struct sockaddr_in6 *addr6 = (struct sockaddr_in6*)&ss;
3414
                                        addr6->sin6_family = AF_INET6;
3415
                                        addr6->sin6_port = 0;
3416
                                        inet_pton(AF_INET6, item->value, &(addr6->sin6_addr.s6_addr));
3417
                                        addrlen = sizeof(struct sockaddr_in6);
3418
                                }
3419
                                r = bind(fd, (const struct sockaddr*)&ss, addrlen);
3420
                                close(fd);
3421
                                if (r < 0) {
3422
                                        JANUS_LOG(LOG_WARN, "Error setting local IP address to %s, falling back to detecting IP address...\n", item->value);
3423
                                } else {
3424
                                        g_strlcpy(local_ip, item->value, sizeof(local_ip));
3425
                                        local_ip_set = TRUE;
3426
                                }
3427
                        }
3428
                }
3429
        }
3430
        if (!local_ip_set)
3431
                janus_detect_local_ip(local_ip, sizeof(local_ip));
3432
        JANUS_LOG(LOG_INFO, "Using %s as local IP...\n", local_ip);
3433

    
3434
        /* Was a custom instance name provided? */
3435
        item = janus_config_get_item_drilldown(config, "general", "server_name");
3436
        if(item && item->value) {
3437
                server_name = g_strdup(item->value);
3438
        }
3439

    
3440
        /* Is there any API secret to consider? */
3441
        api_secret = NULL;
3442
        item = janus_config_get_item_drilldown(config, "general", "api_secret");
3443
        if(item && item->value) {
3444
                api_secret = g_strdup(item->value);
3445
        }
3446
        /* Is there any API secret to consider? */
3447
        admin_api_secret = NULL;
3448
        item = janus_config_get_item_drilldown(config, "general", "admin_secret");
3449
        if(item && item->value) {
3450
                admin_api_secret = g_strdup(item->value);
3451
        }
3452
        /* Also check if the token based authentication mechanism needs to be enabled */
3453
        item = janus_config_get_item_drilldown(config, "general", "token_auth");
3454
        janus_auth_init(item && item->value && janus_is_true(item->value));
3455

    
3456
        /* Setup ICE stuff (e.g., checking if the provided STUN server is correct) */
3457
        char *stun_server = NULL, *turn_server = NULL;
3458
        uint16_t stun_port = 0, turn_port = 0;
3459
        char *turn_type = NULL, *turn_user = NULL, *turn_pwd = NULL;
3460
        char *turn_rest_api = NULL, *turn_rest_api_key = NULL, *turn_rest_api_method = NULL;
3461
        const char *nat_1_1_mapping = NULL;
3462
        uint16_t rtp_min_port = 0, rtp_max_port = 0;
3463
        gboolean ice_lite = FALSE, ice_tcp = FALSE, ipv6 = FALSE;
3464
        item = janus_config_get_item_drilldown(config, "media", "ipv6");
3465
        ipv6 = (item && item->value) ? janus_is_true(item->value) : FALSE;
3466
        item = janus_config_get_item_drilldown(config, "media", "rtp_port_range");
3467
        if(item && item->value) {
3468
                /* Split in min and max port */
3469
                char *maxport = strrchr(item->value, '-');
3470
                if(maxport != NULL) {
3471
                        *maxport = '\0';
3472
                        maxport++;
3473
                        rtp_min_port = atoi(item->value);
3474
                        rtp_max_port = atoi(maxport);
3475
                        maxport--;
3476
                        *maxport = '-';
3477
                }
3478
                if(rtp_min_port > rtp_max_port) {
3479
                        int temp_port = rtp_min_port;
3480
                        rtp_min_port = rtp_max_port;
3481
                        rtp_max_port = temp_port;
3482
                }
3483
                if(rtp_max_port == 0)
3484
                        rtp_max_port = 65535;
3485
                JANUS_LOG(LOG_INFO, "RTP port range: %u -- %u\n", rtp_min_port, rtp_max_port);
3486
        }
3487
        /* Check if we need to enable the ICE Lite mode */
3488
        item = janus_config_get_item_drilldown(config, "nat", "ice_lite");
3489
        ice_lite = (item && item->value) ? janus_is_true(item->value) : FALSE;
3490
        /* Check if we need to enable ICE-TCP support (warning: still broken, for debugging only) */
3491
        item = janus_config_get_item_drilldown(config, "nat", "ice_tcp");
3492
        ice_tcp = (item && item->value) ? janus_is_true(item->value) : FALSE;
3493
        /* Any STUN server to use in Janus? */
3494
        item = janus_config_get_item_drilldown(config, "nat", "stun_server");
3495
        if(item && item->value)
3496
                stun_server = (char *)item->value;
3497
        item = janus_config_get_item_drilldown(config, "nat", "stun_port");
3498
        if(item && item->value)
3499
                stun_port = atoi(item->value);
3500
        /* Any 1:1 NAT mapping to take into account? */
3501
        item = janus_config_get_item_drilldown(config, "nat", "nat_1_1_mapping");
3502
        if(item && item->value) {
3503
                JANUS_LOG(LOG_VERB, "Using nat_1_1_mapping for public ip - %s\n", item->value);
3504
                nat_1_1_mapping = item->value;
3505
                janus_set_public_ip(item->value);
3506
                janus_ice_enable_nat_1_1();
3507
        }
3508
        /* Any TURN server to use in Janus? */
3509
        item = janus_config_get_item_drilldown(config, "nat", "turn_server");
3510
        if(item && item->value)
3511
                turn_server = (char *)item->value;
3512
        item = janus_config_get_item_drilldown(config, "nat", "turn_port");
3513
        if(item && item->value)
3514
                turn_port = atoi(item->value);
3515
        item = janus_config_get_item_drilldown(config, "nat", "turn_type");
3516
        if(item && item->value)
3517
                turn_type = (char *)item->value;
3518
        item = janus_config_get_item_drilldown(config, "nat", "turn_user");
3519
        if(item && item->value)
3520
                turn_user = (char *)item->value;
3521
        item = janus_config_get_item_drilldown(config, "nat", "turn_pwd");
3522
        if(item && item->value)
3523
                turn_pwd = (char *)item->value;
3524
        /* Check if there's any TURN REST API backend to use */
3525
        item = janus_config_get_item_drilldown(config, "nat", "turn_rest_api");
3526
        if(item && item->value)
3527
                turn_rest_api = (char *)item->value;
3528
        item = janus_config_get_item_drilldown(config, "nat", "turn_rest_api_key");
3529
        if(item && item->value)
3530
                turn_rest_api_key = (char *)item->value;
3531
        item = janus_config_get_item_drilldown(config, "nat", "turn_rest_api_method");
3532
        if(item && item->value)
3533
                turn_rest_api_method = (char *)item->value;
3534
        /* Initialize the ICE stack now */
3535
        janus_ice_init(ice_lite, ice_tcp, ipv6, rtp_min_port, rtp_max_port);
3536
        if(janus_ice_set_stun_server(stun_server, stun_port) < 0) {
3537
                JANUS_LOG(LOG_FATAL, "Invalid STUN address %s:%u\n", stun_server, stun_port);
3538
                exit(1);
3539
        }
3540
        if(janus_ice_set_turn_server(turn_server, turn_port, turn_type, turn_user, turn_pwd) < 0) {
3541
                JANUS_LOG(LOG_FATAL, "Invalid TURN address %s:%u\n", turn_server, turn_port);
3542
                exit(1);
3543
        }
3544
#ifndef HAVE_LIBCURL
3545
        if(turn_rest_api != NULL || turn_rest_api_key != NULL) {
3546
                JANUS_LOG(LOG_WARN, "A TURN REST API backend specified in the settings, but libcurl support has not been built\n");
3547
        }
3548
#else
3549
        if(janus_ice_set_turn_rest_api(turn_rest_api, turn_rest_api_key, turn_rest_api_method) < 0) {
3550
                JANUS_LOG(LOG_FATAL, "Invalid TURN REST API configuration: %s (%s, %s)\n", turn_rest_api, turn_rest_api_key, turn_rest_api_method);
3551
                exit(1);
3552
        }
3553
#endif
3554
        item = janus_config_get_item_drilldown(config, "nat", "nice_debug");
3555
        if(item && item->value && janus_is_true(item->value)) {
3556
                /* Enable libnice debugging */
3557
                janus_ice_debugging_enable();
3558
        }
3559
        if(stun_server == NULL && turn_server == NULL) {
3560
                /* No STUN and TURN server provided for Janus: make sure it isn't on a private address */
3561
                gboolean private_address = FALSE;
3562
                const char *test_ip = nat_1_1_mapping ? nat_1_1_mapping : local_ip;
3563
                struct sockaddr_in addr;
3564
                if(inet_pton(AF_INET, test_ip, &addr) > 0) {
3565
                        unsigned short int ip[4];
3566
                        sscanf(test_ip, "%hu.%hu.%hu.%hu", &ip[0], &ip[1], &ip[2], &ip[3]);
3567
                        if(ip[0] == 10) {
3568
                                /* Class A private address */
3569
                                private_address = TRUE;
3570
                        } else if(ip[0] == 172 && (ip[1] >= 16 && ip[1] <= 31)) {
3571
                                /* Class B private address */
3572
                                private_address = TRUE;
3573
                        } else if(ip[0] == 192 && ip[1] == 168) {
3574
                                /* Class C private address */
3575
                                private_address = TRUE;
3576
                        }
3577
                }
3578
                if(private_address) {
3579
                        JANUS_LOG(LOG_WARN, "Janus is deployed on a private address (%s) but you didn't specify any STUN server!"
3580
                                            " Expect trouble if this is supposed to work over the internet and not just in a LAN...\n", test_ip);
3581
                }
3582
        }
3583
        /* Are we going to force BUNDLE and/or rtcp-mux? */
3584
        gboolean force_bundle = FALSE, force_rtcpmux = FALSE;
3585
        item = janus_config_get_item_drilldown(config, "media", "force-bundle");
3586
        force_bundle = (item && item->value) ? janus_is_true(item->value) : FALSE;
3587
        janus_ice_force_bundle(force_bundle);
3588
        item = janus_config_get_item_drilldown(config, "media", "force-rtcp-mux");
3589
        force_rtcpmux = (item && item->value) ? janus_is_true(item->value) : FALSE;
3590
        janus_ice_force_rtcpmux(force_rtcpmux);
3591
        /* NACK related stuff */
3592
        item = janus_config_get_item_drilldown(config, "media", "max_nack_queue");
3593
        if(item && item->value) {
3594
                int mnq = atoi(item->value);
3595
                if(mnq < 0) {
3596
                        JANUS_LOG(LOG_WARN, "Ignoring max_nack_queue value as it's not a positive integer\n");
3597
                } else {
3598
                        janus_set_max_nack_queue(mnq);
3599
                }
3600
        }
3601

    
3602
        /* Setup OpenSSL stuff */
3603
        item = janus_config_get_item_drilldown(config, "certificates", "cert_pem");
3604
        if(!item || !item->value) {
3605
                JANUS_LOG(LOG_FATAL, "Missing certificate/key path, use the command line or the configuration to provide one\n");
3606
                exit(1);
3607
        }
3608
        server_pem = (char *)item->value;
3609
        item = janus_config_get_item_drilldown(config, "certificates", "cert_key");
3610
        if(!item || !item->value) {
3611
                JANUS_LOG(LOG_FATAL, "Missing certificate/key path, use the command line or the configuration to provide one\n");
3612
                exit(1);
3613
        }
3614
        server_key = (char *)item->value;
3615
        JANUS_LOG(LOG_VERB, "Using certificates:\n\t%s\n\t%s\n", server_pem, server_key);
3616
        SSL_library_init();
3617
        SSL_load_error_strings();
3618
        OpenSSL_add_all_algorithms();
3619
        /* ... and DTLS-SRTP in particular */
3620
        if(janus_dtls_srtp_init(server_pem, server_key) < 0) {
3621
                exit(1);
3622
        }
3623
        /* Check if there's any custom value for the starting MTU to use in the BIO filter */
3624
        item = janus_config_get_item_drilldown(config, "media", "dtls_mtu");
3625
        if(item && item->value)
3626
                janus_dtls_bio_filter_set_mtu(atoi(item->value));
3627

    
3628
#ifdef HAVE_SCTP
3629
        /* Initialize SCTP for DataChannels */
3630
        if(janus_sctp_init() < 0) {
3631
                exit(1);
3632
        }
3633
#else
3634
        JANUS_LOG(LOG_WARN, "Data Channels support not compiled\n");
3635
#endif
3636

    
3637
        /* Initialize Sofia-SDP */
3638
        if(janus_sdp_init() < 0) {
3639
                exit(1);
3640
        }
3641

    
3642
        /* Load event handlers */
3643
        const char *path = EVENTDIR;
3644
        item = janus_config_get_item_drilldown(config, "general", "events_folder");
3645
        if(item && item->value)
3646
                path = (char *)item->value;
3647
        JANUS_LOG(LOG_INFO, "Event handler plugins folder: %s\n", path);
3648
        DIR *dir = opendir(path);
3649
        if(!dir) {
3650
                /* Not really fatal, we don't care and go on anyway: event handlers are not fundamental */
3651
                JANUS_LOG(LOG_FATAL, "\tCouldn't access event handler plugins folder...\n");
3652
        } else {
3653
                /* Any event handlers to ignore? */
3654
                gchar **disabled_eventhandlers = NULL;
3655
                item = janus_config_get_item_drilldown(config, "events", "broadcast");
3656
                gboolean enable_events = TRUE;
3657
                if(item && item->value)
3658
                        enable_events = janus_is_true(item->value);
3659
                if(!enable_events) {
3660
                        JANUS_LOG(LOG_WARN, "Event handlers support disabled\n");
3661
                } else {
3662
                        item = janus_config_get_item_drilldown(config, "events", "disable");
3663
                        if(item && item->value)
3664
                                disabled_eventhandlers = g_strsplit(item->value, ",", -1);
3665
                        /* Open the shared objects */
3666
                        struct dirent *eventent = NULL;
3667
                        char eventpath[1024];
3668
                        while((eventent = readdir(dir))) {
3669
                                int len = strlen(eventent->d_name);
3670
                                if (len < 4) {
3671
                                        continue;
3672
                                }
3673
                                if (strcasecmp(eventent->d_name+len-strlen(SHLIB_EXT), SHLIB_EXT)) {
3674
                                        continue;
3675
                                }
3676
                                /* Check if this event handler has been disabled in the configuration file */
3677
                                if(disabled_eventhandlers != NULL) {
3678
                                        gchar *index = disabled_eventhandlers[0];
3679
                                        if(index != NULL) {
3680
                                                int i=0;
3681
                                                gboolean skip = FALSE;
3682
                                                while(index != NULL) {
3683
                                                        while(isspace(*index))
3684
                                                                index++;
3685
                                                        if(strlen(index) && !strcmp(index, eventent->d_name)) {
3686
                                                                JANUS_LOG(LOG_WARN, "Event handler plugin '%s' has been disabled, skipping...\n", eventent->d_name);
3687
                                                                skip = TRUE;
3688
                                                                break;
3689
                                                        }
3690
                                                        i++;
3691
                                                        index = disabled_eventhandlers[i];
3692
                                                }
3693
                                                if(skip)
3694
                                                        continue;
3695
                                        }
3696
                                }
3697
                                JANUS_LOG(LOG_INFO, "Loading event handler plugin '%s'...\n", eventent->d_name);
3698
                                memset(eventpath, 0, 1024);
3699
                                g_snprintf(eventpath, 1024, "%s/%s", path, eventent->d_name);
3700
                                void *event = dlopen(eventpath, RTLD_LAZY);
3701
                                if (!event) {
3702
                                        JANUS_LOG(LOG_ERR, "\tCouldn't load event handler plugin '%s': %s\n", eventent->d_name, dlerror());
3703
                                } else {
3704
                                        create_e *create = (create_e*) dlsym(event, "create");
3705
                                        const char *dlsym_error = dlerror();
3706
                                        if (dlsym_error) {
3707
                                                JANUS_LOG(LOG_ERR, "\tCouldn't load symbol 'create': %s\n", dlsym_error);
3708
                                                continue;
3709
                                        }
3710
                                        janus_eventhandler *janus_eventhandler = create();
3711
                                        if(!janus_eventhandler) {
3712
                                                JANUS_LOG(LOG_ERR, "\tCouldn't use function 'create'...\n");
3713
                                                continue;
3714
                                        }
3715
                                        /* Are all the mandatory methods and callbacks implemented? */
3716
                                        if(!janus_eventhandler->init || !janus_eventhandler->destroy ||
3717
                                                        !janus_eventhandler->get_api_compatibility ||
3718
                                                        !janus_eventhandler->get_version ||
3719
                                                        !janus_eventhandler->get_version_string ||
3720
                                                        !janus_eventhandler->get_description ||
3721
                                                        !janus_eventhandler->get_package ||
3722
                                                        !janus_eventhandler->get_name ||
3723
                                                        !janus_eventhandler->incoming_event) {
3724
                                                JANUS_LOG(LOG_ERR, "\tMissing some mandatory methods/callbacks, skipping this event handler plugin...\n");
3725
                                                continue;
3726
                                        }
3727
                                        if(janus_eventhandler->get_api_compatibility() < JANUS_EVENTHANDLER_API_VERSION) {
3728
                                                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",
3729
                                                        janus_eventhandler->get_package(), janus_eventhandler->get_api_compatibility(), JANUS_EVENTHANDLER_API_VERSION);
3730
                                                continue;
3731
                                        }
3732
                                        janus_eventhandler->init(configs_folder);
3733
                                        JANUS_LOG(LOG_VERB, "\tVersion: %d (%s)\n", janus_eventhandler->get_version(), janus_eventhandler->get_version_string());
3734
                                        JANUS_LOG(LOG_VERB, "\t   [%s] %s\n", janus_eventhandler->get_package(), janus_eventhandler->get_name());
3735
                                        JANUS_LOG(LOG_VERB, "\t   %s\n", janus_eventhandler->get_description());
3736
                                        JANUS_LOG(LOG_VERB, "\t   Plugin API version: %d\n", janus_eventhandler->get_api_compatibility());
3737
                                        JANUS_LOG(LOG_VERB, "\t   Subscriptions:");
3738
                                        if(janus_eventhandler->events_mask == 0) {
3739
                                                JANUS_LOG(LOG_VERB, " none");
3740
                                        } else {
3741
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_SESSION))
3742
                                                        JANUS_LOG(LOG_VERB, " sessions");
3743
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_HANDLE))
3744
                                                        JANUS_LOG(LOG_VERB, " handles");
3745
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_JSEP))
3746
                                                        JANUS_LOG(LOG_VERB, " jsep");
3747
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_WEBRTC))
3748
                                                        JANUS_LOG(LOG_VERB, " webrtc");
3749
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_MEDIA))
3750
                                                        JANUS_LOG(LOG_VERB, " media");
3751
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_PLUGIN))
3752
                                                        JANUS_LOG(LOG_VERB, " plugins");
3753
                                                if(janus_flags_is_set(&janus_eventhandler->events_mask, JANUS_EVENT_TYPE_TRANSPORT))
3754
                                                        JANUS_LOG(LOG_VERB, " transports");
3755
                                        }
3756
                                        JANUS_LOG(LOG_VERB, "\n");
3757
                                        if(eventhandlers == NULL)
3758
                                                eventhandlers = g_hash_table_new(g_str_hash, g_str_equal);
3759
                                        g_hash_table_insert(eventhandlers, (gpointer)janus_eventhandler->get_package(), janus_eventhandler);
3760
                                        if(eventhandlers_so == NULL)
3761
                                                eventhandlers_so = g_hash_table_new(g_str_hash, g_str_equal);
3762
                                        g_hash_table_insert(eventhandlers_so, (gpointer)janus_eventhandler->get_package(), event);
3763
                                }
3764
                        }
3765
                }
3766
                closedir(dir);
3767
                if(disabled_eventhandlers != NULL)
3768
                        g_strfreev(disabled_eventhandlers);
3769
                disabled_eventhandlers = NULL;
3770
                /* Initialize the event broadcaster */
3771
                janus_events_init(enable_events, eventhandlers);
3772
        }
3773

    
3774
        /* Load plugins */
3775
        path = PLUGINDIR;
3776
        item = janus_config_get_item_drilldown(config, "general", "plugins_folder");
3777
        if(item && item->value)
3778
                path = (char *)item->value;
3779
        JANUS_LOG(LOG_INFO, "Plugins folder: %s\n", path);
3780
        dir = opendir(path);
3781
        if(!dir) {
3782
                JANUS_LOG(LOG_FATAL, "\tCouldn't access plugins folder...\n");
3783
                exit(1);
3784
        }
3785
        /* Any plugin to ignore? */
3786
        gchar **disabled_plugins = NULL;
3787
        item = janus_config_get_item_drilldown(config, "plugins", "disable");
3788
        if(item && item->value)
3789
                disabled_plugins = g_strsplit(item->value, ",", -1);
3790
        /* Open the shared objects */
3791
        struct dirent *pluginent = NULL;
3792
        char pluginpath[1024];
3793
        while((pluginent = readdir(dir))) {
3794
                int len = strlen(pluginent->d_name);
3795
                if (len < 4) {
3796
                        continue;
3797
                }
3798
                if (strcasecmp(pluginent->d_name+len-strlen(SHLIB_EXT), SHLIB_EXT)) {
3799
                        continue;
3800
                }
3801
                /* Check if this plugins has been disabled in the configuration file */
3802
                if(disabled_plugins != NULL) {
3803
                        gchar *index = disabled_plugins[0];
3804
                        if(index != NULL) {
3805
                                int i=0;
3806
                                gboolean skip = FALSE;
3807
                                while(index != NULL) {
3808
                                        while(isspace(*index))
3809
                                                index++;
3810
                                        if(strlen(index) && !strcmp(index, pluginent->d_name)) {
3811
                                                JANUS_LOG(LOG_WARN, "Plugin '%s' has been disabled, skipping...\n", pluginent->d_name);
3812
                                                skip = TRUE;
3813
                                                break;
3814
                                        }
3815
                                        i++;
3816
                                        index = disabled_plugins[i];
3817
                                }
3818
                                if(skip)
3819
                                        continue;
3820
                        }
3821
                }
3822
                JANUS_LOG(LOG_INFO, "Loading plugin '%s'...\n", pluginent->d_name);
3823
                memset(pluginpath, 0, 1024);
3824
                g_snprintf(pluginpath, 1024, "%s/%s", path, pluginent->d_name);
3825
                void *plugin = dlopen(pluginpath, RTLD_LOCAL | RTLD_LAZY);
3826
                if (!plugin) {
3827
                        JANUS_LOG(LOG_ERR, "\tCouldn't load plugin '%s': %s\n", pluginent->d_name, dlerror());
3828
                } else {
3829
                        create_p *create = (create_p*) dlsym(plugin, "create");
3830
                        const char *dlsym_error = dlerror();
3831
                        if (dlsym_error) {
3832
                                JANUS_LOG(LOG_ERR, "\tCouldn't load symbol 'create': %s\n", dlsym_error);
3833
                                continue;
3834
                        }
3835
                        janus_plugin *janus_plugin = create();
3836
                        if(!janus_plugin) {
3837
                                JANUS_LOG(LOG_ERR, "\tCouldn't use function 'create'...\n");
3838
                                continue;
3839
                        }
3840
                        /* Are all the mandatory methods and callbacks implemented? */
3841
                        if(!janus_plugin->init || !janus_plugin->destroy ||
3842
                                        !janus_plugin->get_api_compatibility ||
3843
                                        !janus_plugin->get_version ||
3844
                                        !janus_plugin->get_version_string ||
3845
                                        !janus_plugin->get_description ||
3846
                                        !janus_plugin->get_package ||
3847
                                        !janus_plugin->get_name ||
3848
                                        !janus_plugin->create_session ||
3849
                                        !janus_plugin->query_session ||
3850
                                        !janus_plugin->destroy_session ||
3851
                                        !janus_plugin->handle_message ||
3852
                                        !janus_plugin->setup_media ||
3853
                                        !janus_plugin->hangup_media) {
3854
                                JANUS_LOG(LOG_ERR, "\tMissing some mandatory methods/callbacks, skipping this plugin...\n");
3855
                                continue;
3856
                        }
3857
                        if(janus_plugin->get_api_compatibility() < JANUS_PLUGIN_API_VERSION) {
3858
                                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",
3859
                                        janus_plugin->get_package(), janus_plugin->get_api_compatibility(), JANUS_PLUGIN_API_VERSION);
3860
                                continue;
3861
                        }
3862
                        janus_plugin->init(&janus_handler_plugin, configs_folder);
3863
                        JANUS_LOG(LOG_VERB, "\tVersion: %d (%s)\n", janus_plugin->get_version(), janus_plugin->get_version_string());
3864
                        JANUS_LOG(LOG_VERB, "\t   [%s] %s\n", janus_plugin->get_package(), janus_plugin->get_name());
3865
                        JANUS_LOG(LOG_VERB, "\t   %s\n", janus_plugin->get_description());
3866
                        JANUS_LOG(LOG_VERB, "\t   Plugin API version: %d\n", janus_plugin->get_api_compatibility());
3867
                        if(!janus_plugin->incoming_rtp && !janus_plugin->incoming_rtcp && !janus_plugin->incoming_data) {
3868
                                JANUS_LOG(LOG_WARN, "The '%s' plugin doesn't implement any callback for RTP/RTCP/data... is this on purpose?\n",
3869
                                        janus_plugin->get_package());
3870
                        }
3871
                        if(!janus_plugin->incoming_rtp && !janus_plugin->incoming_rtcp && janus_plugin->incoming_data) {
3872
                                JANUS_LOG(LOG_WARN, "The '%s' plugin will only handle data channels (no RTP/RTCP)... is this on purpose?\n",
3873
                                        janus_plugin->get_package());
3874
                        }
3875
                        if(plugins == NULL)
3876
                                plugins = g_hash_table_new(g_str_hash, g_str_equal);
3877
                        g_hash_table_insert(plugins, (gpointer)janus_plugin->get_package(), janus_plugin);
3878
                        if(plugins_so == NULL)
3879
                                plugins_so = g_hash_table_new(g_str_hash, g_str_equal);
3880
                        g_hash_table_insert(plugins_so, (gpointer)janus_plugin->get_package(), plugin);
3881
                }
3882
        }
3883
        closedir(dir);
3884
        if(disabled_plugins != NULL)
3885
                g_strfreev(disabled_plugins);
3886
        disabled_plugins = NULL;
3887

    
3888
        /* Create a thread pool to handle incoming requests, no matter what the transport */
3889
        GError *error = NULL;
3890
        tasks = g_thread_pool_new(janus_transport_task, NULL, -1, FALSE, &error);
3891
        if(error != NULL) {
3892
                /* Something went wrong... */
3893
                JANUS_LOG(LOG_FATAL, "Got error %d (%s) trying to launch the request pool task thread...\n", error->code, error->message ? error->message : "??");
3894
                exit(1);
3895
        }
3896

    
3897
        /* Load transports */
3898
        gboolean janus_api_enabled = FALSE, admin_api_enabled = FALSE;
3899
        path = TRANSPORTDIR;
3900
        item = janus_config_get_item_drilldown(config, "general", "transports_folder");
3901
        if(item && item->value)
3902
                path = (char *)item->value;
3903
        JANUS_LOG(LOG_INFO, "Transport plugins folder: %s\n", path);
3904
        dir = opendir(path);
3905
        if(!dir) {
3906
                JANUS_LOG(LOG_FATAL, "\tCouldn't access transport plugins folder...\n");
3907
                exit(1);
3908
        }
3909
        /* Any transport to ignore? */
3910
        gchar **disabled_transports = NULL;
3911
        item = janus_config_get_item_drilldown(config, "transports", "disable");
3912
        if(item && item->value)
3913
                disabled_transports = g_strsplit(item->value, ",", -1);
3914
        /* Open the shared objects */
3915
        struct dirent *transportent = NULL;
3916
        char transportpath[1024];
3917
        while((transportent = readdir(dir))) {
3918
                int len = strlen(transportent->d_name);
3919
                if (len < 4) {
3920
                        continue;
3921
                }
3922
                if (strcasecmp(transportent->d_name+len-strlen(SHLIB_EXT), SHLIB_EXT)) {
3923
                        continue;
3924
                }
3925
                /* Check if this transports has been disabled in the configuration file */
3926
                if(disabled_transports != NULL) {
3927
                        gchar *index = disabled_transports[0];
3928
                        if(index != NULL) {
3929
                                int i=0;
3930
                                gboolean skip = FALSE;
3931
                                while(index != NULL) {
3932
                                        while(isspace(*index))
3933
                                                index++;
3934
                                        if(strlen(index) && !strcmp(index, transportent->d_name)) {
3935
                                                JANUS_LOG(LOG_WARN, "Transport plugin '%s' ha