Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_sip.c @ a6079d3d

History | View | Annotate | Download (127 KB)

1
/*! \file   janus_sip.c
2
 * \author Lorenzo Miniero <lorenzo@meetecho.com>
3
 * \copyright GNU General Public License v3
4
 * \brief  Janus SIP plugin
5
 * \details  This is a simple SIP plugin for Janus, allowing WebRTC peers
6
 * to register at a SIP server (e.g., Asterisk) and call SIP user agents
7
 * through the gateway. Specifically, when attaching to the plugin peers
8
 * are requested to provide their SIP server credentials, i.e., the address
9
 * of the SIP server and their username/secret. This results in the plugin
10
 * registering at the SIP server and acting as a SIP client on behalf of
11
 * the web peer. Most of the SIP states and lifetime are masked by the plugin,
12
 * and only the relevant events (e.g., INVITEs and BYEs) and functionality
13
 * (call, hangup) are made available to the web peer: peers can call
14
 * extensions at the SIP server or wait for incoming INVITEs, and during
15
 * a call they can send DTMF tones. Calls can do plain RTP or SDES-SRTP.
16
 *
17
 * The concept behind this plugin is to allow different web pages associated
18
 * to the same peer, and hence the same SIP user, to attach to the plugin
19
 * at the same time and yet just do a SIP REGISTER once. The same should
20
 * apply for calls: while an incoming call would be notified to all the
21
 * web UIs associated to the peer, only one would be able to pick up and
22
 * answer, in pretty much the same way as SIP forking works but without the
23
 * need to fork in the same place. This specific functionality, though, has
24
 * not been implemented as of yet.
25
 *
26
 * \todo Only Asterisk and Kamailio have been tested as a SIP server, and
27
 * specifically only with basic audio calls: this plugin needs some work
28
 * to make it more stable and reliable.
29
 *
30
 * \section sipapi SIP Plugin API
31
 *
32
 * All requests you can send in the SIP Plugin API are asynchronous,
33
 * which means all responses (successes and errors) will be delivered
34
 * as events with the same transaction.
35
 *
36
 * The supported requests are \c register , \c call , \c accept and
37
 * \c hangup . \c register can be used, as the name suggests, to register
38
 * a username at a SIP registrar to call and be called; \c call is used
39
 * to send an INVITE to a different SIP URI through the plugin, while
40
 * \c accept is used to accept the call in case one is invited instead
41
 * of inviting; finally, \c hangup can be used to terminate the
42
 * communication at any time, either to hangup (BYE) an ongoing call or
43
 * to cancel/decline (CANCEL/BYE) a call that hasn't started yet.
44
 *
45
 * Actual API docs: TBD.
46
 *
47
 * \ingroup plugins
48
 * \ref plugins
49
 */
50

    
51
#include "plugin.h"
52

    
53
#include <arpa/inet.h>
54
#include <net/if.h>
55

    
56
#include <jansson.h>
57

    
58
#include <sofia-sip/msg_header.h>
59
#include <sofia-sip/nua.h>
60
#include <sofia-sip/sdp.h>
61
#include <sofia-sip/sip_status.h>
62
#include <sofia-sip/url.h>
63
#include <sofia-sip/tport_tag.h>
64

    
65
#include <srtp/srtp.h>
66
#include <srtp/crypto_kernel.h>
67

    
68
#include "../debug.h"
69
#include "../apierror.h"
70
#include "../config.h"
71
#include "../mutex.h"
72
#include "../record.h"
73
#include "../rtp.h"
74
#include "../rtcp.h"
75
#include "../utils.h"
76

    
77

    
78
/* Plugin information */
79
#define JANUS_SIP_VERSION                        6
80
#define JANUS_SIP_VERSION_STRING        "0.0.6"
81
#define JANUS_SIP_DESCRIPTION                "This is a simple SIP plugin for Janus, allowing WebRTC peers to register at a SIP server and call SIP user agents through the gateway."
82
#define JANUS_SIP_NAME                                "JANUS SIP plugin"
83
#define JANUS_SIP_AUTHOR                        "Meetecho s.r.l."
84
#define JANUS_SIP_PACKAGE                        "janus.plugin.sip"
85

    
86
/* Plugin methods */
87
janus_plugin *create(void);
88
int janus_sip_init(janus_callbacks *callback, const char *config_path);
89
void janus_sip_destroy(void);
90
int janus_sip_get_api_compatibility(void);
91
int janus_sip_get_version(void);
92
const char *janus_sip_get_version_string(void);
93
const char *janus_sip_get_description(void);
94
const char *janus_sip_get_name(void);
95
const char *janus_sip_get_author(void);
96
const char *janus_sip_get_package(void);
97
void janus_sip_create_session(janus_plugin_session *handle, int *error);
98
struct janus_plugin_result *janus_sip_handle_message(janus_plugin_session *handle, char *transaction, char *message, char *sdp_type, char *sdp);
99
void janus_sip_setup_media(janus_plugin_session *handle);
100
void janus_sip_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len);
101
void janus_sip_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len);
102
void janus_sip_hangup_media(janus_plugin_session *handle);
103
void janus_sip_destroy_session(janus_plugin_session *handle, int *error);
104
char *janus_sip_query_session(janus_plugin_session *handle);
105

    
106
/* Plugin setup */
107
static janus_plugin janus_sip_plugin =
108
        JANUS_PLUGIN_INIT (
109
                .init = janus_sip_init,
110
                .destroy = janus_sip_destroy,
111

    
112
                .get_api_compatibility = janus_sip_get_api_compatibility,
113
                .get_version = janus_sip_get_version,
114
                .get_version_string = janus_sip_get_version_string,
115
                .get_description = janus_sip_get_description,
116
                .get_name = janus_sip_get_name,
117
                .get_author = janus_sip_get_author,
118
                .get_package = janus_sip_get_package,
119

    
120
                .create_session = janus_sip_create_session,
121
                .handle_message = janus_sip_handle_message,
122
                .setup_media = janus_sip_setup_media,
123
                .incoming_rtp = janus_sip_incoming_rtp,
124
                .incoming_rtcp = janus_sip_incoming_rtcp,
125
                .hangup_media = janus_sip_hangup_media,
126
                .destroy_session = janus_sip_destroy_session,
127
                .query_session = janus_sip_query_session,
128
        );
129

    
130
/* Plugin creator */
131
janus_plugin *create(void) {
132
        JANUS_LOG(LOG_VERB, "%s created!\n", JANUS_SIP_NAME);
133
        return &janus_sip_plugin;
134
}
135

    
136

    
137
/* Useful stuff */
138
static volatile gint initialized = 0, stopping = 0;
139
static janus_callbacks *gateway = NULL;
140

    
141
static char local_ip[INET6_ADDRSTRLEN];
142
static int keepalive_interval = 120;
143
static gboolean behind_nat = FALSE;
144
static char *user_agent;
145
#define JANUS_DEFAULT_REGISTER_TTL        3600
146
static int register_ttl = JANUS_DEFAULT_REGISTER_TTL;
147

    
148
static GThread *handler_thread;
149
static GThread *watchdog;
150
static void *janus_sip_handler(void *data);
151

    
152
typedef struct janus_sip_message {
153
        janus_plugin_session *handle;
154
        char *transaction;
155
        char *message;
156
        char *sdp_type;
157
        char *sdp;
158
} janus_sip_message;
159
static GAsyncQueue *messages = NULL;
160
static janus_sip_message exit_message;
161

    
162
static void janus_sip_message_free(janus_sip_message *msg) {
163
        if(!msg || msg == &exit_message)
164
                return;
165

    
166
        msg->handle = NULL;
167

    
168
        g_free(msg->transaction);
169
        msg->transaction = NULL;
170
        g_free(msg->message);
171
        msg->message = NULL;
172
        g_free(msg->sdp_type);
173
        msg->sdp_type = NULL;
174
        g_free(msg->sdp);
175
        msg->sdp = NULL;
176

    
177
        g_free(msg);
178
}
179

    
180

    
181
typedef enum {
182
        janus_sip_registration_status_disabled = -2,
183
        janus_sip_registration_status_failed = -1,
184
        janus_sip_registration_status_unregistered = 0,
185
        janus_sip_registration_status_registering,
186
        janus_sip_registration_status_registered,
187
        janus_sip_registration_status_unregistering,
188
} janus_sip_registration_status;
189

    
190
static const char *janus_sip_registration_status_string(janus_sip_registration_status status) {
191
        switch(status) {
192
                case janus_sip_registration_status_disabled:
193
                        return "disabled";
194
                case janus_sip_registration_status_failed:
195
                        return "failed";
196
                case janus_sip_registration_status_unregistered:
197
                        return "unregistered";
198
                case janus_sip_registration_status_registering:
199
                        return "registering";
200
                case janus_sip_registration_status_registered:
201
                        return "registered";
202
                case janus_sip_registration_status_unregistering:
203
                        return "unregistering";
204
                default:
205
                        return "unknown";
206
        }
207
}
208

    
209

    
210
typedef enum {
211
        janus_sip_call_status_idle = 0,
212
        janus_sip_call_status_inviting,
213
        janus_sip_call_status_invited,
214
        janus_sip_call_status_incall,
215
        janus_sip_call_status_closing,
216
} janus_sip_call_status;
217

    
218
static const char *janus_sip_call_status_string(janus_sip_call_status status) {
219
        switch(status) {
220
                case janus_sip_call_status_idle:
221
                        return "idle";
222
                case janus_sip_call_status_inviting:
223
                        return "inviting";
224
                case janus_sip_call_status_invited:
225
                        return "invited";
226
                case janus_sip_call_status_incall:
227
                        return "incall";
228
                case janus_sip_call_status_closing:
229
                        return "closing";
230
                default:
231
                        return "unknown";
232
        }
233
}
234

    
235

    
236
/* Sofia stuff */
237
typedef struct ssip_s ssip_t;
238
typedef struct ssip_oper_s ssip_oper_t;
239

    
240
typedef enum {
241
        janus_sip_secret_type_plaintext = 1,
242
        janus_sip_secret_type_hashed = 2,
243
        janus_sip_secret_type_unknown
244
} janus_sip_secret_type;
245

    
246
typedef struct janus_sip_account {
247
        char *identity;
248
        gboolean sips;
249
        char *username;
250
        char *authuser;                        /**< username to use for authentication */
251
        char *secret;
252
        janus_sip_secret_type secret_type;
253
        int sip_port;
254
        char *proxy;
255
        janus_sip_registration_status registration_status;
256
} janus_sip_account;
257

    
258
typedef struct janus_sip_media {
259
        char *remote_ip;
260
        int ready:1;
261
        gboolean require_srtp, has_srtp_local, has_srtp_remote;
262
        int has_audio:1;
263
        int audio_rtp_fd, audio_rtcp_fd;
264
        int local_audio_rtp_port, remote_audio_rtp_port;
265
        int local_audio_rtcp_port, remote_audio_rtcp_port;
266
        guint32 audio_ssrc, audio_ssrc_peer;
267
        srtp_t audio_srtp_in, audio_srtp_out;
268
        srtp_policy_t audio_remote_policy, audio_local_policy;
269
        int audio_srtp_suite_in, audio_srtp_suite_out;
270
        int has_video:1;
271
        int video_rtp_fd, video_rtcp_fd;
272
        int local_video_rtp_port, remote_video_rtp_port;
273
        int local_video_rtcp_port, remote_video_rtcp_port;
274
        guint32 video_ssrc, video_ssrc_peer;
275
        srtp_t video_srtp_in, video_srtp_out;
276
        srtp_policy_t video_remote_policy, video_local_policy;
277
        int video_srtp_suite_in, video_srtp_suite_out;
278
} janus_sip_media;
279

    
280
typedef struct janus_sip_session {
281
        janus_plugin_session *handle;
282
        ssip_t *stack;
283
        janus_sip_account account;
284
        janus_sip_call_status status;
285
        janus_sip_media media;
286
        char *transaction;
287
        char *callee;
288
        janus_recorder *arc;                /* The Janus recorder instance for this user's audio, if enabled */
289
        janus_recorder *arc_peer;        /* The Janus recorder instance for the peer's audio, if enabled */
290
        janus_recorder *vrc;                /* The Janus recorder instance for this user's video, if enabled */
291
        janus_recorder *vrc_peer;        /* The Janus recorder instance for the peer's video, if enabled */
292
        volatile gint hangingup;
293
        gint64 destroyed;        /* Time at which this session was marked as destroyed */
294
        janus_mutex mutex;
295
} janus_sip_session;
296
static GHashTable *sessions;
297
static GList *old_sessions;
298
static janus_mutex sessions_mutex;
299

    
300

    
301
#undef SU_ROOT_MAGIC_T
302
#define SU_ROOT_MAGIC_T        ssip_t
303
#undef NUA_MAGIC_T
304
#define NUA_MAGIC_T                ssip_t
305
#undef NUA_HMAGIC_T
306
#define NUA_HMAGIC_T        ssip_oper_t
307

    
308
struct ssip_s {
309
        su_home_t s_home[1];
310
        su_root_t *s_root;
311
        nua_t *s_nua;
312
        nua_handle_t *s_nh_r, *s_nh_i;
313
        janus_sip_session *session;
314
};
315

    
316

    
317
/* SRTP stuff (in case we need SDES) */
318
#define SRTP_MASTER_KEY_LENGTH        16
319
#define SRTP_MASTER_SALT_LENGTH        14
320
#define SRTP_MASTER_LENGTH (SRTP_MASTER_KEY_LENGTH + SRTP_MASTER_SALT_LENGTH)
321
static const char *janus_sip_srtp_error[] =
322
{
323
        "err_status_ok",
324
        "err_status_fail",
325
        "err_status_bad_param",
326
        "err_status_alloc_fail",
327
        "err_status_dealloc_fail",
328
        "err_status_init_fail",
329
        "err_status_terminus",
330
        "err_status_auth_fail",
331
        "err_status_cipher_fail",
332
        "err_status_replay_fail",
333
        "err_status_replay_old",
334
        "err_status_algo_fail",
335
        "err_status_no_such_op",
336
        "err_status_no_ctx",
337
        "err_status_cant_check",
338
        "err_status_key_expired",
339
        "err_status_socket_err",
340
        "err_status_signal_err",
341
        "err_status_nonce_bad",
342
        "err_status_read_fail",
343
        "err_status_write_fail",
344
        "err_status_parse_err",
345
        "err_status_encode_err",
346
        "err_status_semaphore_err",
347
        "err_status_pfkey_err",
348
};
349
static const gchar *janus_sip_get_srtp_error(int error) {
350
        if(error < 0 || error > 24)
351
                return NULL;
352
        return janus_sip_srtp_error[error];
353
}
354
static int janus_sip_srtp_set_local(janus_sip_session *session, gboolean video, char **crypto) {
355
        if(session == NULL)
356
                return -1;
357
        /* Generate key/salt */
358
        uint8_t *key = g_malloc0(SRTP_MASTER_LENGTH);
359
        crypto_get_random(key, SRTP_MASTER_LENGTH);
360
        /* Set SRTP policies */
361
        srtp_policy_t *policy = video ? &session->media.video_local_policy : &session->media.audio_local_policy;
362
        crypto_policy_set_rtp_default(&(policy->rtp));
363
        crypto_policy_set_rtcp_default(&(policy->rtcp));
364
        policy->ssrc.type = ssrc_any_inbound;
365
        policy->key = key;
366
        policy->next = NULL;
367
        /* Create SRTP context */
368
        err_status_t res = srtp_create(video ? &session->media.video_srtp_out : &session->media.audio_srtp_out, policy);
369
        if(res != err_status_ok) {
370
                /* Something went wrong... */
371
                JANUS_LOG(LOG_ERR, "Oops, error creating outbound SRTP session: %d (%s)\n", res, janus_sip_get_srtp_error(res));
372
                g_free(key);
373
                policy->key = NULL;
374
                return -2;
375
        }
376
        /* Base64 encode the salt */
377
        *crypto = g_base64_encode(key, SRTP_MASTER_LENGTH);
378
        if((video && session->media.video_srtp_out) || (!video && session->media.audio_srtp_out)) {
379
                JANUS_LOG(LOG_VERB, "%s outbound SRTP session created\n", video ? "Video" : "Audio");
380
        }
381
        return 0;
382
}
383
static int janus_sip_srtp_set_remote(janus_sip_session *session, gboolean video, const char *crypto, int suite) {
384
        if(session == NULL || crypto == NULL)
385
                return -1;
386
        /* Base64 decode the crypto string and set it as the remote SRTP context */
387
        gsize len = 0;
388
        guchar *decoded = g_base64_decode(crypto, &len);
389
        if(len < SRTP_MASTER_LENGTH) {
390
                /* FIXME Can this happen? */
391
                g_free(decoded);
392
                return -2;
393
        }
394
        /* Set SRTP policies */
395
        srtp_policy_t *policy = video ? &session->media.video_remote_policy : &session->media.audio_remote_policy;
396
        crypto_policy_set_rtp_default(&(policy->rtp));
397
        crypto_policy_set_rtcp_default(&(policy->rtcp));
398
        if(suite == 32) {
399
                crypto_policy_set_aes_cm_128_hmac_sha1_32(&(policy->rtp));
400
                crypto_policy_set_aes_cm_128_hmac_sha1_32(&(policy->rtcp));
401
        } else if(suite == 80) {
402
                crypto_policy_set_aes_cm_128_hmac_sha1_80(&(policy->rtp));
403
                crypto_policy_set_aes_cm_128_hmac_sha1_80(&(policy->rtcp));
404
        }
405
        policy->ssrc.type = ssrc_any_inbound;
406
        policy->key = decoded;
407
        policy->next = NULL;
408
        /* Create SRTP context */
409
        err_status_t res = srtp_create(video ? &session->media.video_srtp_in : &session->media.audio_srtp_in, policy);
410
        if(res != err_status_ok) {
411
                /* Something went wrong... */
412
                JANUS_LOG(LOG_ERR, "Oops, error creating inbound SRTP session: %d (%s)\n", res, janus_sip_get_srtp_error(res));
413
                g_free(decoded);
414
                policy->key = NULL;
415
                return -2;
416
        }
417
        if((video && session->media.video_srtp_in) || (!video && session->media.audio_srtp_in)) {
418
                JANUS_LOG(LOG_VERB, "%s inbound SRTP session created\n", video ? "Video" : "Audio");
419
        }
420
        return 0;
421
}
422
static void janus_sip_srtp_cleanup(janus_sip_session *session) {
423
        if(session == NULL)
424
                return;
425
        session->media.require_srtp = FALSE;
426
        session->media.has_srtp_local = FALSE;
427
        session->media.has_srtp_remote = FALSE;
428
        /* Audio */
429
        if(session->media.audio_srtp_out)
430
                srtp_dealloc(session->media.audio_srtp_out);
431
        session->media.audio_srtp_out = NULL;
432
        g_free(session->media.audio_local_policy.key);
433
        session->media.audio_local_policy.key = NULL;
434
        session->media.audio_srtp_suite_out = 0;
435
        if(session->media.audio_srtp_in)
436
                srtp_dealloc(session->media.audio_srtp_in);
437
        session->media.audio_srtp_in = NULL;
438
        g_free(session->media.audio_remote_policy.key);
439
        session->media.audio_remote_policy.key = NULL;
440
        session->media.audio_srtp_suite_in = 0;
441
        /* Video */
442
        if(session->media.video_srtp_out)
443
                srtp_dealloc(session->media.video_srtp_out);
444
        session->media.video_srtp_out = NULL;
445
        g_free(session->media.video_local_policy.key);
446
        session->media.video_local_policy.key = NULL;
447
        session->media.video_srtp_suite_out = 0;
448
        if(session->media.video_srtp_in)
449
                srtp_dealloc(session->media.video_srtp_in);
450
        session->media.video_srtp_in = NULL;
451
        g_free(session->media.video_remote_policy.key);
452
        session->media.video_remote_policy.key = NULL;
453
        session->media.video_srtp_suite_in = 0;
454
}
455

    
456

    
457
/* Sofia Event thread */
458
gpointer janus_sip_sofia_thread(gpointer user_data);
459
/* Sofia callbacks */
460
void janus_sip_sofia_callback(nua_event_t event, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[]);
461
/* SDP parsing and manipulation */
462
void janus_sip_sdp_process(janus_sip_session *session, sdp_session_t *sdp);
463
char *janus_sip_sdp_manipulate(janus_sip_session *session, sdp_session_t *sdp);
464
/* Media */
465
static int janus_sip_allocate_local_ports(janus_sip_session *session);
466
static void *janus_sip_relay_thread(void *data);
467

    
468

    
469
/* URI parsing utilies */
470

    
471
#define JANUS_SIP_URI_MAXLEN        1024
472
typedef struct {
473
        char data[JANUS_SIP_URI_MAXLEN];
474
        url_t url[1];
475
} janus_sip_uri_t;
476

    
477
/* Parses a SIP URI (SIPS is not supported), returns 0 on success, -1 otherwise */
478
static int janus_sip_parse_uri(janus_sip_uri_t *sip_uri, const char *data) {
479
        g_strlcpy(sip_uri->data, data, JANUS_SIP_URI_MAXLEN);
480
        if (url_d(sip_uri->url, sip_uri->data) < 0 || sip_uri->url->url_type != url_sip)
481
                return -1;
482
        return 0;
483
}
484

    
485
/* Similar to the above function, but it also accepts SIPS URIs */
486
static int janus_sip_parse_proxy_uri(janus_sip_uri_t *sip_uri, const char *data) {
487
        g_strlcpy(sip_uri->data, data, JANUS_SIP_URI_MAXLEN);
488
        if (url_d(sip_uri->url, sip_uri->data) < 0 || (sip_uri->url->url_type != url_sip && sip_uri->url->url_type != url_sips))
489
                return -1;
490
        return 0;
491
}
492

    
493
/* Error codes */
494
#define JANUS_SIP_ERROR_UNKNOWN_ERROR                499
495
#define JANUS_SIP_ERROR_NO_MESSAGE                        440
496
#define JANUS_SIP_ERROR_INVALID_JSON                441
497
#define JANUS_SIP_ERROR_INVALID_REQUEST                442
498
#define JANUS_SIP_ERROR_MISSING_ELEMENT                443
499
#define JANUS_SIP_ERROR_INVALID_ELEMENT                444
500
#define JANUS_SIP_ERROR_ALREADY_REGISTERED        445
501
#define JANUS_SIP_ERROR_INVALID_ADDRESS                446
502
#define JANUS_SIP_ERROR_WRONG_STATE                        447
503
#define JANUS_SIP_ERROR_MISSING_SDP                        448
504
#define JANUS_SIP_ERROR_LIBSOFIA_ERROR                449
505
#define JANUS_SIP_ERROR_IO_ERROR                        450
506
#define JANUS_SIP_ERROR_RECORDING_ERROR                451
507
#define JANUS_SIP_ERROR_TOO_STRICT                        452
508

    
509

    
510
/* SIP watchdog/garbage collector (sort of) */
511
void *janus_sip_watchdog(void *data);
512
void *janus_sip_watchdog(void *data) {
513
        JANUS_LOG(LOG_INFO, "SIP watchdog started\n");
514
        gint64 now = 0;
515
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
516
                janus_mutex_lock(&sessions_mutex);
517
                /* Iterate on all the sessions */
518
                now = janus_get_monotonic_time();
519
                if(old_sessions != NULL) {
520
                        GList *sl = old_sessions;
521
                        JANUS_LOG(LOG_HUGE, "Checking %d old SIP sessions...\n", g_list_length(old_sessions));
522
                        while(sl) {
523
                                janus_sip_session *session = (janus_sip_session *)sl->data;
524
                                if(!session) {
525
                                        sl = sl->next;
526
                                        continue;
527
                                }
528
                                if (now-session->destroyed >= 5*G_USEC_PER_SEC) {
529
                                        /* We're lazy and actually get rid of the stuff only after a few seconds */
530
                                        JANUS_LOG(LOG_VERB, "Freeing old SIP session\n");
531
                                        GList *rm = sl->next;
532
                                        old_sessions = g_list_delete_link(old_sessions, sl);
533
                                        sl = rm;
534
                                        if (session->account.identity) {
535
                                            g_free(session->account.identity);
536
                                            session->account.identity = NULL;
537
                                        }
538
                                        session->account.sips = TRUE;
539
                                        if (session->account.proxy) {
540
                                            g_free(session->account.proxy);
541
                                            session->account.proxy = NULL;
542
                                        }
543
                                        if (session->account.secret) {
544
                                            g_free(session->account.secret);
545
                                            session->account.secret = NULL;
546
                                        }
547
                                        if (session->account.username) {
548
                                            g_free(session->account.username);
549
                                            session->account.username = NULL;
550
                                        }
551
                                        if (session->account.authuser) {
552
                                            g_free(session->account.authuser);
553
                                            session->account.authuser = NULL;
554
                                        }
555
                                        if (session->callee) {
556
                                            g_free(session->callee);
557
                                            session->callee = NULL;
558
                                        }
559
                                        if (session->transaction) {
560
                                            g_free(session->transaction);
561
                                            session->transaction = NULL;
562
                                        }
563
                                        if (session->media.remote_ip) {
564
                                            g_free(session->media.remote_ip);
565
                                            session->media.remote_ip = NULL;
566
                                        }
567
                                        janus_sip_srtp_cleanup(session);
568
                                        session->handle = NULL;
569
                                        g_free(session);
570
                                        session = NULL;
571
                                        continue;
572
                                }
573
                                sl = sl->next;
574
                        }
575
                }
576
                janus_mutex_unlock(&sessions_mutex);
577
                g_usleep(500000);
578
        }
579
        JANUS_LOG(LOG_INFO, "SIP watchdog stopped\n");
580
        return NULL;
581
}
582

    
583

    
584
static void janus_sip_detect_local_ip(char *buf, size_t buflen) {
585
        JANUS_LOG(LOG_VERB, "Autodetecting local IP...\n");
586

    
587
        struct sockaddr_in addr;
588
        socklen_t len;
589
        int fd = socket(AF_INET, SOCK_DGRAM, 0);
590
        if (fd == -1)
591
                goto error;
592
        addr.sin_family = AF_INET;
593
        addr.sin_port = htons(1);
594
        inet_pton(AF_INET, "1.2.3.4", &addr.sin_addr.s_addr);
595
        if (connect(fd, (const struct sockaddr*) &addr, sizeof(addr)) < 0)
596
                goto error;
597
        len = sizeof(addr);
598
        if (getsockname(fd, (struct sockaddr*) &addr, &len) < 0)
599
                goto error;
600
        if (getnameinfo((const struct sockaddr*) &addr, sizeof(addr),
601
                        buf, buflen,
602
                        NULL, 0, NI_NUMERICHOST) != 0)
603
                goto error;
604
        close(fd);
605
        return;
606

    
607
error:
608
        if (fd != -1)
609
                close(fd);
610
        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");
611
        g_strlcpy(buf, "127.0.0.1", buflen);
612
}
613

    
614

    
615
/* Plugin implementation */
616
int janus_sip_init(janus_callbacks *callback, const char *config_path) {
617
        if(g_atomic_int_get(&stopping)) {
618
                /* Still stopping from before */
619
                return -1;
620
        }
621
        if(callback == NULL || config_path == NULL) {
622
                /* Invalid arguments */
623
                return -1;
624
        }
625

    
626
        /* Read configuration */
627
        char filename[255];
628
        g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_SIP_PACKAGE);
629
        JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
630
        janus_config *config = janus_config_parse(filename);
631
        if(config != NULL)
632
                janus_config_print(config);
633

    
634
        gboolean local_ip_set = FALSE;
635
        janus_config_item *item = janus_config_get_item_drilldown(config, "general", "local_ip");
636
        if(item && item->value) {
637
                int family;
638
                if (!janus_is_ip_valid(item->value, &family)) {
639
                        JANUS_LOG(LOG_WARN, "Invalid local IP specified: %s, guessing the default...\n", item->value);
640
                } else {
641
                        /* Verify that we can actually bind to that address */
642
                        int fd = socket(family, SOCK_DGRAM, 0);
643
                        if (fd == -1) {
644
                                JANUS_LOG(LOG_WARN, "Error creating test socket, falling back to detecting IP address...\n");
645
                        } else {
646
                                int r;
647
                                struct sockaddr_storage ss;
648
                                socklen_t addrlen;
649
                                memset(&ss, 0, sizeof(ss));
650
                                if (family == AF_INET) {
651
                                        struct sockaddr_in *addr4 = (struct sockaddr_in*)&ss;
652
                                        addr4->sin_family = AF_INET;
653
                                        addr4->sin_port = 0;
654
                                        inet_pton(AF_INET, item->value, &(addr4->sin_addr.s_addr));
655
                                        addrlen = sizeof(struct sockaddr_in);
656
                                } else {
657
                                        struct sockaddr_in6 *addr6 = (struct sockaddr_in6*)&ss;
658
                                        addr6->sin6_family = AF_INET6;
659
                                        addr6->sin6_port = 0;
660
                                        inet_pton(AF_INET6, item->value, &(addr6->sin6_addr.s6_addr));
661
                                        addrlen = sizeof(struct sockaddr_in6);
662
                                }
663
                                r = bind(fd, (const struct sockaddr*)&ss, addrlen);
664
                                close(fd);
665
                                if (r < 0) {
666
                                        JANUS_LOG(LOG_WARN, "Error setting local IP address to %s, falling back to detecting IP address...\n", item->value);
667
                                } else {
668
                                        g_strlcpy(local_ip, item->value, sizeof(local_ip));
669
                                        local_ip_set = TRUE;
670
                                }
671
                        }
672
                }
673
        }
674
        if (!local_ip_set)
675
                janus_sip_detect_local_ip(local_ip, sizeof(local_ip));
676
        JANUS_LOG(LOG_VERB, "Local IP set to %s\n", local_ip);
677

    
678
        item = janus_config_get_item_drilldown(config, "general", "keepalive_interval");
679
        if(item && item->value)
680
                keepalive_interval = atoi(item->value);
681
        JANUS_LOG(LOG_VERB, "SIP keep-alive interval set to %d seconds\n", keepalive_interval);
682

    
683
        item = janus_config_get_item_drilldown(config, "general", "register_ttl");
684
        if(item && item->value)
685
                register_ttl = atoi(item->value);
686
        JANUS_LOG(LOG_VERB, "SIP registration TTL set to %d seconds\n", register_ttl);
687

    
688
        item = janus_config_get_item_drilldown(config, "general", "behind_nat");
689
        if(item && item->value)
690
                behind_nat = janus_is_true(item->value);
691

    
692
        item = janus_config_get_item_drilldown(config, "general", "user_agent");
693
        if(item && item->value)
694
                user_agent = g_strdup(item->value);
695
        else
696
                user_agent = g_strdup("Janus WebRTC Gateway SIP Plugin "JANUS_SIP_VERSION_STRING);
697
        JANUS_LOG(LOG_VERB, "SIP User-Agent set to %s\n", user_agent);
698

    
699
        /* This plugin actually has nothing to configure... */
700
        janus_config_destroy(config);
701
        config = NULL;
702

    
703
        /* Setup sofia */
704
        su_init();
705

    
706
        sessions = g_hash_table_new(NULL, NULL);
707
        janus_mutex_init(&sessions_mutex);
708
        messages = g_async_queue_new_full((GDestroyNotify) janus_sip_message_free);
709
        /* This is the callback we'll need to invoke to contact the gateway */
710
        gateway = callback;
711

    
712
        g_atomic_int_set(&initialized, 1);
713

    
714
        GError *error = NULL;
715
        /* Start the sessions watchdog */
716
        watchdog = g_thread_try_new("etest watchdog", &janus_sip_watchdog, NULL, &error);
717
        if(error != NULL) {
718
                g_atomic_int_set(&initialized, 0);
719
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP watchdog thread...\n", error->code, error->message ? error->message : "??");
720
                return -1;
721
        }
722
        /* Launch the thread that will handle incoming messages */
723
        handler_thread = g_thread_try_new("janus sip handler", janus_sip_handler, NULL, &error);
724
        if(error != NULL) {
725
                g_atomic_int_set(&initialized, 0);
726
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP handler thread...\n", error->code, error->message ? error->message : "??");
727
                return -1;
728
        }
729
        JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_SIP_NAME);
730
        return 0;
731
}
732

    
733
void janus_sip_destroy(void) {
734
        if(!g_atomic_int_get(&initialized))
735
                return;
736
        g_atomic_int_set(&stopping, 1);
737

    
738
        g_async_queue_push(messages, &exit_message);
739
        if(handler_thread != NULL) {
740
                g_thread_join(handler_thread);
741
                handler_thread = NULL;
742
        }
743
        if(watchdog != NULL) {
744
                g_thread_join(watchdog);
745
                watchdog = NULL;
746
        }
747
        /* FIXME We should destroy the sessions cleanly */
748
        janus_mutex_lock(&sessions_mutex);
749
        g_hash_table_destroy(sessions);
750
        janus_mutex_unlock(&sessions_mutex);
751
        g_async_queue_unref(messages);
752
        messages = NULL;
753
        sessions = NULL;
754
        g_atomic_int_set(&initialized, 0);
755
        g_atomic_int_set(&stopping, 0);
756
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_SIP_NAME);
757
}
758

    
759
int janus_sip_get_api_compatibility(void) {
760
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
761
        return JANUS_PLUGIN_API_VERSION;
762
}
763

    
764
int janus_sip_get_version(void) {
765
        return JANUS_SIP_VERSION;
766
}
767

    
768
const char *janus_sip_get_version_string(void) {
769
        return JANUS_SIP_VERSION_STRING;
770
}
771

    
772
const char *janus_sip_get_description(void) {
773
        return JANUS_SIP_DESCRIPTION;
774
}
775

    
776
const char *janus_sip_get_name(void) {
777
        return JANUS_SIP_NAME;
778
}
779

    
780
const char *janus_sip_get_author(void) {
781
        return JANUS_SIP_AUTHOR;
782
}
783

    
784
const char *janus_sip_get_package(void) {
785
        return JANUS_SIP_PACKAGE;
786
}
787

    
788
void janus_sip_create_session(janus_plugin_session *handle, int *error) {
789
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
790
                *error = -1;
791
                return;
792
        }
793
        janus_sip_session *session = g_malloc0(sizeof(janus_sip_session));
794
        session->handle = handle;
795
        session->account.identity = NULL;
796
        session->account.sips = TRUE;
797
        session->account.username = NULL;
798
        session->account.authuser = NULL;
799
        session->account.secret = NULL;
800
        session->account.secret_type = janus_sip_secret_type_unknown;
801
        session->account.sip_port = 0;
802
        session->account.proxy = NULL;
803
        session->account.registration_status = janus_sip_registration_status_unregistered;
804
        session->status = janus_sip_call_status_idle;
805
        session->stack = NULL;
806
        session->transaction = NULL;
807
        session->callee = NULL;
808
        session->media.remote_ip = NULL;
809
        session->media.ready = 0;
810
        session->media.require_srtp = FALSE;
811
        session->media.has_srtp_local = FALSE;
812
        session->media.has_srtp_remote = FALSE;
813
        session->media.has_audio = 0;
814
        session->media.audio_rtp_fd = -1;
815
        session->media.audio_rtcp_fd= -1;
816
        session->media.local_audio_rtp_port = 0;
817
        session->media.remote_audio_rtp_port = 0;
818
        session->media.local_audio_rtcp_port = 0;
819
        session->media.remote_audio_rtcp_port = 0;
820
        session->media.audio_ssrc = 0;
821
        session->media.audio_ssrc_peer = 0;
822
        session->media.audio_srtp_suite_in = 0;
823
        session->media.audio_srtp_suite_out = 0;
824
        session->media.has_video = 0;
825
        session->media.video_rtp_fd = -1;
826
        session->media.video_rtcp_fd= -1;
827
        session->media.local_video_rtp_port = 0;
828
        session->media.remote_video_rtp_port = 0;
829
        session->media.local_video_rtcp_port = 0;
830
        session->media.remote_video_rtcp_port = 0;
831
        session->media.video_ssrc = 0;
832
        session->media.video_ssrc_peer = 0;
833
        session->media.video_srtp_suite_in = 0;
834
        session->media.video_srtp_suite_out = 0;
835
        session->destroyed = 0;
836
        g_atomic_int_set(&session->hangingup, 0);
837
        janus_mutex_init(&session->mutex);
838
        handle->plugin_handle = session;
839

    
840
        janus_mutex_lock(&sessions_mutex);
841
        g_hash_table_insert(sessions, handle, session);
842
        janus_mutex_unlock(&sessions_mutex);
843

    
844
        return;
845
}
846

    
847
void janus_sip_destroy_session(janus_plugin_session *handle, int *error) {
848
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
849
                *error = -1;
850
                return;
851
        }
852
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
853
        if(!session) {
854
                JANUS_LOG(LOG_ERR, "No SIP session associated with this handle...\n");
855
                *error = -2;
856
                return;
857
        }
858
        janus_mutex_lock(&sessions_mutex);
859
        if(!session->destroyed) {
860
                g_hash_table_remove(sessions, handle);
861
                janus_sip_hangup_media(handle);
862
                session->destroyed = janus_get_monotonic_time();
863
                JANUS_LOG(LOG_VERB, "Destroying SIP session (%s)...\n", session->account.username ? session->account.username : "unregistered user");
864
                if(session->stack != NULL) {
865
                        /* Shutdown the NUA: this will remove the session later on */
866
                        nua_shutdown(session->stack->s_nua);
867
                } else {
868
                        /* No stack, maybe never registered: cleaning up and removing the session is done in a lazy way */
869
                        old_sessions = g_list_append(old_sessions, session);
870
                }
871
        }
872
        janus_mutex_unlock(&sessions_mutex);
873
        return;
874
}
875

    
876
char *janus_sip_query_session(janus_plugin_session *handle) {
877
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
878
                return NULL;
879
        }
880
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
881
        if(!session) {
882
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
883
                return NULL;
884
        }
885
        /* Provide some generic info, e.g., if we're in a call and with whom */
886
        json_t *info = json_object();
887
        json_object_set_new(info, "username", session->account.username ? json_string(session->account.username) : NULL);
888
        json_object_set_new(info, "identity", session->account.identity ? json_string(session->account.identity) : NULL);
889
        json_object_set_new(info, "registration_status", json_string(janus_sip_registration_status_string(session->account.registration_status)));
890
        json_object_set_new(info, "call_status", json_string(janus_sip_call_status_string(session->status)));
891
        if(session->callee) {
892
                json_object_set_new(info, "callee", json_string(session->callee ? session->callee : "??"));
893
                json_object_set_new(info, "srtp-required", json_string(session->media.require_srtp ? "yes" : "no"));
894
                json_object_set_new(info, "sdes-local", json_string(session->media.has_srtp_local ? "yes" : "no"));
895
                json_object_set_new(info, "sdes-remote", json_string(session->media.has_srtp_remote ? "yes" : "no"));
896
        }
897
        if(session->arc || session->vrc || session->arc_peer || session->vrc_peer) {
898
                json_t *recording = json_object();
899
                if(session->arc && session->arc->filename)
900
                        json_object_set_new(recording, "audio", json_string(session->arc->filename));
901
                if(session->vrc && session->vrc->filename)
902
                        json_object_set_new(recording, "video", json_string(session->vrc->filename));
903
                if(session->arc_peer && session->arc_peer->filename)
904
                        json_object_set_new(recording, "audio-peer", json_string(session->arc_peer->filename));
905
                if(session->vrc_peer && session->vrc_peer->filename)
906
                        json_object_set_new(recording, "video-peer", json_string(session->vrc_peer->filename));
907
                json_object_set_new(info, "recording", recording);
908
        }
909
        json_object_set_new(info, "destroyed", json_integer(session->destroyed));
910
        char *info_text = json_dumps(info, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
911
        json_decref(info);
912
        return info_text;
913
}
914

    
915
struct janus_plugin_result *janus_sip_handle_message(janus_plugin_session *handle, char *transaction, char *message, char *sdp_type, char *sdp) {
916
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
917
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized");
918
        JANUS_LOG(LOG_VERB, "%s\n", message);
919
        janus_sip_message *msg = g_malloc0(sizeof(janus_sip_message));
920
        msg->handle = handle;
921
        msg->transaction = transaction;
922
        msg->message = message;
923
        msg->sdp_type = sdp_type;
924
        msg->sdp = sdp;
925
        g_async_queue_push(messages, msg);
926

    
927
        /* All the requests to this plugin are handled asynchronously */
928
        return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL);
929
}
930

    
931
void janus_sip_setup_media(janus_plugin_session *handle) {
932
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
933
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
934
                return;
935
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
936
        if(!session) {
937
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
938
                return;
939
        }
940
        if(session->destroyed)
941
                return;
942
        g_atomic_int_set(&session->hangingup, 0);
943
        /* TODO Only relay RTP/RTCP when we get this event */
944
}
945

    
946
void janus_sip_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len) {
947
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
948
                return;
949
        if(gateway) {
950
                /* Honour the audio/video active flags */
951
                janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
952
                if(!session || session->destroyed) {
953
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
954
                        return;
955
                }
956
                if(session->status != janus_sip_call_status_incall)
957
                        return;
958
                /* Forward to our SIP peer */
959
                if(video) {
960
                        if(session->media.video_ssrc == 0) {
961
                                rtp_header *header = (rtp_header *)buf;
962
                                session->media.video_ssrc = ntohl(header->ssrc);
963
                                JANUS_LOG(LOG_VERB, "Got SIP video SSRC: %"SCNu32"\n", session->media.video_ssrc);
964
                        }
965
                        if(session->media.has_video && session->media.video_rtp_fd) {
966
                                /* Save the frame if we're recording */
967
                                if(session->vrc)
968
                                        janus_recorder_save_frame(session->vrc, buf, len);
969
                                /* Is SRTP involved? */
970
                                if(session->media.has_srtp_local) {
971
                                        char sbuf[2048];
972
                                        memcpy(&sbuf, buf, len);
973
                                        int protected = len;
974
                                        int res = srtp_protect(session->media.video_srtp_out, &sbuf, &protected);
975
                                        if(res != err_status_ok) {
976
                                                rtp_header *header = (rtp_header *)&sbuf;
977
                                                guint32 timestamp = ntohl(header->timestamp);
978
                                                guint16 seq = ntohs(header->seq_number);
979
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTP protect error... %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")...\n",
980
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected, timestamp, seq);
981
                                        } else {
982
                                                /* Forward the frame to the peer */
983
                                                send(session->media.video_rtp_fd, sbuf, protected, 0);
984
                                        }
985
                                } else {
986
                                        /* Forward the frame to the peer */
987
                                        send(session->media.video_rtp_fd, buf, len, 0);
988
                                }
989
                        }
990
                } else {
991
                        if(session->media.audio_ssrc == 0) {
992
                                rtp_header *header = (rtp_header *)buf;
993
                                session->media.audio_ssrc = ntohl(header->ssrc);
994
                                JANUS_LOG(LOG_VERB, "Got SIP audio SSRC: %"SCNu32"\n", session->media.audio_ssrc);
995
                        }
996
                        if(session->media.has_audio && session->media.audio_rtp_fd) {
997
                                /* Save the frame if we're recording */
998
                                if(session->arc)
999
                                        janus_recorder_save_frame(session->arc, buf, len);
1000
                                /* Is SRTP involved? */
1001
                                if(session->media.has_srtp_local) {
1002
                                        char sbuf[2048];
1003
                                        memcpy(&sbuf, buf, len);
1004
                                        int protected = len;
1005
                                        int res = srtp_protect(session->media.audio_srtp_out, &sbuf, &protected);
1006
                                        if(res != err_status_ok) {
1007
                                                rtp_header *header = (rtp_header *)&sbuf;
1008
                                                guint32 timestamp = ntohl(header->timestamp);
1009
                                                guint16 seq = ntohs(header->seq_number);
1010
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTP protect error... %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")...\n",
1011
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected, timestamp, seq);
1012
                                        } else {
1013
                                                /* Forward the frame to the peer */
1014
                                                send(session->media.audio_rtp_fd, sbuf, protected, 0);
1015
                                        }
1016
                                } else {
1017
                                        /* Forward the frame to the peer */
1018
                                        send(session->media.audio_rtp_fd, buf, len, 0);
1019
                                }
1020
                        }
1021
                }
1022
        }
1023
}
1024

    
1025
void janus_sip_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
1026
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1027
                return;
1028
        if(gateway) {
1029
                janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1030
                if(!session || session->destroyed) {
1031
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1032
                        return;
1033
                }
1034
                if(session->status != janus_sip_call_status_incall)
1035
                        return;
1036
                /* Forward to our SIP peer */
1037
                if(video) {
1038
                        if(session->media.has_video && session->media.video_rtcp_fd) {
1039
                                /* Is SRTP involved? */
1040
                                if(session->media.has_srtp_local) {
1041
                                        char sbuf[2048];
1042
                                        memcpy(&sbuf, buf, len);
1043
                                        int protected = len;
1044
                                        int res = srtp_protect_rtcp(session->media.video_srtp_out, &sbuf, &protected);
1045
                                        if(res != err_status_ok) {
1046
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTCP protect error... %s (len=%d-->%d)...\n",
1047
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected);
1048
                                        } else {
1049
                                                /* Fix SSRCs as the gateway does */
1050
                                                JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1051
                                                        session->media.video_ssrc, session->media.video_ssrc_peer);
1052
                                                janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.video_ssrc, session->media.video_ssrc_peer);
1053
                                                /* Forward the message to the peer */
1054
                                                send(session->media.video_rtcp_fd, sbuf, protected, 0);
1055
                                        }
1056
                                } else {
1057
                                        /* Fix SSRCs as the gateway does */
1058
                                        JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1059
                                                session->media.video_ssrc, session->media.video_ssrc_peer);
1060
                                        janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.video_ssrc, session->media.video_ssrc_peer);
1061
                                        /* Forward the message to the peer */
1062
                                        send(session->media.video_rtcp_fd, buf, len, 0);
1063
                                }
1064
                        }
1065
                } else {
1066
                        if(session->media.has_audio && session->media.audio_rtcp_fd) {
1067
                                /* Is SRTP involved? */
1068
                                if(session->media.has_srtp_local) {
1069
                                        char sbuf[2048];
1070
                                        memcpy(&sbuf, buf, len);
1071
                                        int protected = len;
1072
                                        int res = srtp_protect_rtcp(session->media.audio_srtp_out, &sbuf, &protected);
1073
                                        if(res != err_status_ok) {
1074
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTCP protect error... %s (len=%d-->%d)...\n",
1075
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected);
1076
                                        } else {
1077
                                                /* Fix SSRCs as the gateway does */
1078
                                                JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1079
                                                        session->media.audio_ssrc, session->media.audio_ssrc_peer);
1080
                                                janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.audio_ssrc, session->media.audio_ssrc_peer);
1081
                                                /* Forward the message to the peer */
1082
                                                send(session->media.audio_rtcp_fd, sbuf, protected, 0);
1083
                                        }
1084
                                } else {
1085
                                        /* Fix SSRCs as the gateway does */
1086
                                        JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1087
                                                session->media.audio_ssrc, session->media.audio_ssrc_peer);
1088
                                        janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.audio_ssrc, session->media.audio_ssrc_peer);
1089
                                        /* Forward the message to the peer */
1090
                                        send(session->media.audio_rtcp_fd, buf, len, 0);
1091
                                }
1092
                        }
1093
                }
1094
        }
1095
}
1096

    
1097
void janus_sip_hangup_media(janus_plugin_session *handle) {
1098
        JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
1099
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1100
                return;
1101
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1102
        if(!session) {
1103
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1104
                return;
1105
        }
1106
        if(session->destroyed)
1107
                return;
1108
        if(g_atomic_int_add(&session->hangingup, 1))
1109
                return;
1110
        if(!(session->status == janus_sip_call_status_inviting ||
1111
                 session->status == janus_sip_call_status_invited ||
1112
                 session->status == janus_sip_call_status_incall))
1113
                return;
1114
        /* Get rid of the recorders, if available */
1115
        if(session->arc) {
1116
                janus_recorder_close(session->arc);
1117
                JANUS_LOG(LOG_INFO, "Closed user's audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
1118
                janus_recorder_free(session->arc);
1119
        }
1120
        session->arc = NULL;
1121
        if(session->arc_peer) {
1122
                janus_recorder_close(session->arc_peer);
1123
                JANUS_LOG(LOG_INFO, "Closed peer's audio recording %s\n", session->arc_peer->filename ? session->arc_peer->filename : "??");
1124
                janus_recorder_free(session->arc_peer);
1125
        }
1126
        session->arc_peer = NULL;
1127
        if(session->vrc) {
1128
                janus_recorder_close(session->vrc);
1129
                JANUS_LOG(LOG_INFO, "Closed user's video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
1130
                janus_recorder_free(session->vrc);
1131
        }
1132
        session->vrc = NULL;
1133
        if(session->vrc_peer) {
1134
                janus_recorder_close(session->vrc_peer);
1135
                JANUS_LOG(LOG_INFO, "Closed peer's video recording %s\n", session->vrc_peer->filename ? session->vrc_peer->filename : "??");
1136
                janus_recorder_free(session->vrc_peer);
1137
        }
1138
        session->vrc_peer = NULL;
1139
        /* FIXME Simulate a "hangup" coming from the browser */
1140
        janus_sip_message *msg = g_malloc0(sizeof(janus_sip_message));
1141
        msg->handle = handle;
1142
        msg->message = g_strdup("{\"request\":\"hangup\"}");
1143
        msg->transaction = NULL;
1144
        msg->sdp_type = NULL;
1145
        msg->sdp = NULL;
1146
        g_async_queue_push(messages, msg);
1147
}
1148

    
1149
/* Thread to handle incoming messages */
1150
static void *janus_sip_handler(void *data) {
1151
        JANUS_LOG(LOG_VERB, "Joining SIP handler thread\n");
1152
        janus_sip_message *msg = NULL;
1153
        int error_code = 0;
1154
        char *error_cause = g_malloc0(512);
1155
        json_t *root = NULL;
1156
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
1157
                msg = g_async_queue_pop(messages);
1158
                if(msg == NULL)
1159
                        continue;
1160
                if(msg == &exit_message)
1161
                        break;
1162
                if(msg->handle == NULL) {
1163
                        janus_sip_message_free(msg);
1164
                        continue;
1165
                }
1166
                janus_sip_session *session = NULL;
1167
                janus_mutex_lock(&sessions_mutex);
1168
                if(g_hash_table_lookup(sessions, msg->handle) != NULL ) {
1169
                        session = (janus_sip_session *)msg->handle->plugin_handle;
1170
                }
1171
                janus_mutex_unlock(&sessions_mutex);
1172
                if(!session) {
1173
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1174
                        janus_sip_message_free(msg);
1175
                        continue;
1176
                }
1177
                if(session->destroyed) {
1178
                        janus_sip_message_free(msg);
1179
                        continue;
1180
                }
1181
                /* Handle request */
1182
                error_code = 0;
1183
                root = NULL;
1184
                JANUS_LOG(LOG_VERB, "Handling message: %s\n", msg->message);
1185
                if(msg->message == NULL) {
1186
                        JANUS_LOG(LOG_ERR, "No message??\n");
1187
                        error_code = JANUS_SIP_ERROR_NO_MESSAGE;
1188
                        g_snprintf(error_cause, 512, "%s", "No message??");
1189
                        goto error;
1190
                }
1191
                json_error_t error;
1192
                root = json_loads(msg->message, 0, &error);
1193
                if(!root) {
1194
                        JANUS_LOG(LOG_ERR, "JSON error: on line %d: %s\n", error.line, error.text);
1195
                        error_code = JANUS_SIP_ERROR_INVALID_JSON;
1196
                        g_snprintf(error_cause, 512, "JSON error: on line %d: %s", error.line, error.text);
1197
                        goto error;
1198
                }
1199
                if(!json_is_object(root)) {
1200
                        JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
1201
                        error_code = JANUS_SIP_ERROR_INVALID_JSON;
1202
                        g_snprintf(error_cause, 512, "JSON error: not an object");
1203
                        goto error;
1204
                }
1205
                json_t *request = json_object_get(root, "request");
1206
                if(!request) {
1207
                        JANUS_LOG(LOG_ERR, "Missing element (request)\n");
1208
                        error_code = JANUS_SIP_ERROR_MISSING_ELEMENT;
1209
                        g_snprintf(error_cause, 512, "Missing element (request)");
1210
                        goto error;
1211
                }
1212
                if(!json_is_string(request)) {
1213
                        JANUS_LOG(LOG_ERR, "Invalid element (request should be a string)\n");
1214
                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1215
                        g_snprintf(error_cause, 512, "Invalid element (request should be a string)");
1216
                        goto error;
1217
                }
1218
                const char *request_text = json_string_value(request);
1219
                json_t *result = NULL;
1220
                char *sdp_type = NULL, *sdp = NULL;
1221

    
1222
                if(!strcasecmp(request_text, "register")) {
1223
                        /* Send a REGISTER */
1224
                        if(session->account.registration_status > janus_sip_registration_status_unregistered) {
1225
                                JANUS_LOG(LOG_ERR, "Already registered (%s)\n", session->account.username);
1226
                                error_code = JANUS_SIP_ERROR_ALREADY_REGISTERED;
1227
                                g_snprintf(error_cause, 512, "Already registered (%s)", session->account.username);
1228
                                goto error;
1229
                        }
1230

    
1231
                        /* Cleanup old values */
1232
                        if(session->account.identity != NULL)
1233
                                g_free(session->account.identity);
1234
                        session->account.identity = NULL;
1235
                        session->account.sips = TRUE;
1236
                        if(session->account.username != NULL)
1237
                                g_free(session->account.username);
1238
                        session->account.username = NULL;
1239
                        if(session->account.authuser != NULL)
1240
                                g_free(session->account.authuser);
1241
                        session->account.authuser = NULL;
1242
                        if(session->account.secret != NULL)
1243
                                g_free(session->account.secret);
1244
                        session->account.secret = NULL;
1245
                        session->account.secret_type = janus_sip_secret_type_unknown;
1246
                        if(session->account.proxy != NULL)
1247
                                g_free(session->account.proxy);
1248
                        session->account.proxy = NULL;
1249
                        session->account.registration_status = janus_sip_registration_status_unregistered;
1250

    
1251
                        gboolean guest = FALSE;
1252
                        json_t *type = json_object_get(root, "type");
1253
                        if(type != NULL) {
1254
                                if(!json_is_string(type)) {
1255
                                        JANUS_LOG(LOG_ERR, "Invalid element (type should be a string)\n");
1256
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1257
                                        g_snprintf(error_cause, 512, "Invalid element (type should be a string)");
1258
                                        goto error;
1259
                                }
1260
                                const char *type_text = json_string_value(type);
1261
                                if(!strcmp(type_text, "guest")) {
1262
                                        JANUS_LOG(LOG_INFO, "Registering as a guest\n");
1263
                                        guest = TRUE;
1264
                                } else {
1265
                                        JANUS_LOG(LOG_WARN, "Unknown type '%s', ignoring...\n", type_text);
1266
                                }
1267
                        }
1268

    
1269
                        gboolean send_register = TRUE;
1270
                        json_t *do_register = json_object_get(root, "send_register");
1271
                        if(do_register != NULL) {
1272
                                if(!json_is_boolean(do_register)) {
1273
                                        JANUS_LOG(LOG_ERR, "Invalid element (send_register should be boolean)\n");
1274
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1275
                                        g_snprintf(error_cause, 512, "Invalid element (send_register should be boolean)");
1276
                                        goto error;
1277
                                }
1278
                                if(guest) {
1279
                                        JANUS_LOG(LOG_ERR, "Conflicting elements: send_register cannot be true if guest is true\n");
1280
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1281
                                        g_snprintf(error_cause, 512, "Conflicting elements: send_register cannot be true if guest is true");
1282
                                        goto error;
1283
                                }
1284
                                send_register = json_is_true(do_register);
1285
                        }
1286

    
1287
                        gboolean sips = TRUE;
1288
                        json_t *do_sips = json_object_get(root, "sips");
1289
                        if(do_sips != NULL) {
1290
                                if(!json_is_boolean(do_sips)) {
1291
                                        JANUS_LOG(LOG_ERR, "Invalid element (sips should be boolean)\n");
1292
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1293
                                        g_snprintf(error_cause, 512, "Invalid element (sips should be boolean)");
1294
                                        goto error;
1295
                                }
1296
                                sips = json_is_true(do_sips);
1297
                        }
1298

    
1299
                        /* Parse address */
1300
                        json_t *proxy = json_object_get(root, "proxy");
1301
                        const char *proxy_text = NULL;
1302

    
1303
                        if (proxy && !json_is_null(proxy)) {
1304
                                if(!json_is_string(proxy)) {
1305
                                        JANUS_LOG(LOG_ERR, "Invalid element (proxy should be a string)\n");
1306
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1307
                                        g_snprintf(error_cause, 512, "Invalid element (proxy should be a string)");
1308
                                        goto error;
1309
                                }
1310
                                proxy_text = json_string_value(proxy);
1311
                                janus_sip_uri_t proxy_uri;
1312
                                if (janus_sip_parse_proxy_uri(&proxy_uri, proxy_text) < 0) {
1313
                                        JANUS_LOG(LOG_ERR, "Invalid proxy address %s\n", proxy_text);
1314
                                        error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1315
                                        g_snprintf(error_cause, 512, "Invalid proxy address %s\n", proxy_text);
1316
                                        goto error;
1317
                                }
1318
                        }
1319

    
1320
                        /* Parse register TTL */
1321
                        int ttl = register_ttl;
1322
                        json_t *reg_ttl = json_object_get(root, "register_ttl");
1323
                        if (reg_ttl && json_is_integer(reg_ttl))
1324
                                ttl = json_integer_value(reg_ttl);
1325
                        if (ttl <= 0)
1326
                                ttl = JANUS_DEFAULT_REGISTER_TTL;
1327

    
1328
                        /* Now the user part, if needed */
1329
                        json_t *username = json_object_get(root, "username");
1330
                        if(!guest && !username) {
1331
                                /* The username is mandatory if we're not registering as guests */
1332
                                JANUS_LOG(LOG_ERR, "Missing element (username)\n");
1333
                                error_code = JANUS_SIP_ERROR_MISSING_ELEMENT;
1334
                                g_snprintf(error_cause, 512, "Missing element (username)");
1335
                                goto error;
1336
                        }
1337
                        const char *username_text = NULL;
1338
                        janus_sip_uri_t username_uri;
1339
                        char user_id[256];
1340
                        if(username) {
1341
                                if(!json_is_string(username)) {
1342
                                        JANUS_LOG(LOG_ERR, "Invalid element (username should be a string)\n");
1343
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1344
                                        g_snprintf(error_cause, 512, "Invalid element (username should be a string)");
1345
                                        goto error;
1346
                                }
1347
                                /* Parse address */
1348
                                username_text = json_string_value(username);
1349
                                if (janus_sip_parse_uri(&username_uri, username_text) < 0) {
1350
                                        JANUS_LOG(LOG_ERR, "Invalid user address %s\n", username_text);
1351
                                        error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1352
                                        g_snprintf(error_cause, 512, "Invalid user address %s\n", username_text);
1353
                                        goto error;
1354
                                }
1355
                                g_strlcpy(user_id, username_uri.url->url_user, sizeof(user_id));
1356
                        }
1357
                        if(guest) {
1358
                                /* Not needed, we can stop here: just pick a random username if it wasn't provided and say we're registered */
1359
                                if(!username)
1360
                                        g_snprintf(user_id, 255, "janus-sip-%"SCNu32"", g_random_int());
1361
                                JANUS_LOG(LOG_INFO, "Guest will have username %s\n", user_id);
1362
                                send_register = FALSE;
1363
                        } else {
1364
                                json_t *secret = json_object_get(root, "secret");
1365
                                json_t *ha1_secret = json_object_get(root, "ha1_secret");
1366
                                json_t *authuser = json_object_get(root, "authuser");
1367
                                if(!secret && !ha1_secret) {
1368
                                        JANUS_LOG(LOG_ERR, "Missing element (secret or ha1_secret)\n");
1369
                                        error_code = JANUS_SIP_ERROR_MISSING_ELEMENT;
1370
                                        g_snprintf(error_cause, 512, "Missing element (secret or ha1_secret)");
1371
                                        goto error;
1372
                                }
1373
                                if(secret && ha1_secret) {
1374
                                        JANUS_LOG(LOG_ERR, "Conflicting elements specified (secret and ha1_secret)\n");
1375
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1376
                                        g_snprintf(error_cause, 512, "Conflicting elements specified (secret and ha1_secret)");
1377
                                        goto error;
1378
                                }
1379
                                const char *secret_text;
1380
                                if(secret) {
1381
                                        if(!json_is_string(secret)) {
1382
                                                JANUS_LOG(LOG_ERR, "Invalid element (secret should be a string)\n");
1383
                                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1384
                                                g_snprintf(error_cause, 512, "Invalid element (secret should be a string)");
1385
                                                goto error;
1386
                                        }
1387
                                        secret_text = json_string_value(secret);
1388
                                        session->account.secret = g_strdup(secret_text);
1389
                                        session->account.secret_type = janus_sip_secret_type_plaintext;
1390
                                } else {
1391
                                        if(!json_is_string(ha1_secret)) {
1392
                                                JANUS_LOG(LOG_ERR, "Invalid element (ha1_secret should be a string)\n");
1393
                                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1394
                                                g_snprintf(error_cause, 512, "Invalid element (ha1_secret should be a string)");
1395
                                                goto error;
1396
                                        }
1397
                                        secret_text = json_string_value(ha1_secret);
1398
                                        session->account.secret = g_strdup(secret_text);
1399
                                        session->account.secret_type = janus_sip_secret_type_hashed;
1400
                                }
1401
                                if (authuser) {
1402
                                        const char *authuser_text;
1403
                                        if (!json_is_string(authuser)) {
1404
                                                JANUS_LOG(LOG_ERR, "Invalid element (authentication username should be a string)\n");
1405
                                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1406
                                                g_snprintf(error_cause, 512, "Invalid element (authentication username should be a string)");
1407
                                                goto error;
1408
                                        }
1409
                                        authuser_text = json_string_value(authuser);
1410
                                        session->account.authuser = g_strdup(authuser_text);
1411
                                } else {
1412
                                        session->account.authuser = g_strdup(user_id);
1413
                                }
1414
                                /* Got the values, try registering now */
1415
                                JANUS_LOG(LOG_VERB, "Registering user %s (secret %s) @ %s through %s\n",
1416
                                        username_text, secret_text, username_uri.url->url_host, proxy_text != NULL ? proxy_text : "(null)");
1417
                        }
1418

    
1419
                        session->account.identity = g_strdup(username_text);
1420
                        session->account.sips = sips;
1421
                        session->account.username = g_strdup(user_id);
1422
                        if (proxy_text) {
1423
                                session->account.proxy = g_strdup(proxy_text);
1424
                        }
1425

    
1426
                        session->account.registration_status = janus_sip_registration_status_registering;
1427
                        if(session->stack == NULL) {
1428
                                /* Start the thread first */
1429
                                GError *error = NULL;
1430
                                g_thread_try_new("worker", janus_sip_sofia_thread, session, &error);
1431
                                if(error != NULL) {
1432
                                        JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP Sofia thread...\n", error->code, error->message ? error->message : "??");
1433
                                        error_code = JANUS_SIP_ERROR_UNKNOWN_ERROR;
1434
                                        g_snprintf(error_cause, 512, "Got error %d (%s) trying to launch the SIP Sofia thread", error->code, error->message ? error->message : "??");
1435
                                        goto error;
1436
                                }
1437
                                long int timeout = 0;
1438
                                while(session->stack == NULL || session->stack->s_nua == NULL) {
1439
                                        g_usleep(100000);
1440
                                        timeout += 100000;
1441
                                        if(timeout >= 2000000) {
1442
                                                break;
1443
                                        }
1444
                                }
1445
                                if(timeout >= 2000000) {
1446
                                        JANUS_LOG(LOG_ERR, "Two seconds passed and still no NUA, problems with the thread?\n");
1447
                                        error_code = JANUS_SIP_ERROR_UNKNOWN_ERROR;
1448
                                        g_snprintf(error_cause, 512, "Two seconds passed and still no NUA, problems with the thread?");
1449
                                        goto error;
1450
                                }
1451
                        }
1452
                        if(session->stack->s_nh_r != NULL) {
1453
                                nua_handle_destroy(session->stack->s_nh_r);
1454
                                session->stack->s_nh_r = NULL;
1455
                        }
1456

    
1457
                        if (send_register) {
1458
                                session->stack->s_nh_r = nua_handle(session->stack->s_nua, session, TAG_END());
1459
                                if(session->stack->s_nh_r == NULL) {
1460
                                        JANUS_LOG(LOG_ERR, "NUA Handle for REGISTER still null??\n");
1461
                                        error_code = JANUS_SIP_ERROR_LIBSOFIA_ERROR;
1462
                                        g_snprintf(error_cause, 512, "Invalid NUA Handle");
1463
                                        goto error;
1464
                                }
1465
                                char ttl_text[20];
1466
                                g_snprintf(ttl_text, sizeof(ttl_text), "%d", ttl);
1467
                                nua_register(session->stack->s_nh_r,
1468
                                        NUTAG_M_USERNAME(session->account.username),
1469
                                        SIPTAG_FROM_STR(username_text),
1470
                                        SIPTAG_TO_STR(username_text),
1471
                                        SIPTAG_EXPIRES_STR(ttl_text),
1472
                                        NUTAG_PROXY(proxy_text),
1473
                                        TAG_END());
1474
                                result = json_object();
1475
                                json_object_set_new(result, "event", json_string("registering"));
1476
                        } else {
1477
                                JANUS_LOG(LOG_VERB, "Not sending a SIP REGISTER: either send_register was set to false or guest mode was enabled\n");
1478
                                session->account.registration_status = janus_sip_registration_status_disabled;
1479
                                result = json_object();
1480
                                json_object_set_new(result, "event", json_string("registered"));
1481
                                json_object_set_new(result, "username", json_string(session->account.username));
1482
                                json_object_set_new(result, "register_sent", json_string("false"));
1483
                        }
1484
                } else if(!strcasecmp(request_text, "call")) {
1485
                        /* Call another peer */
1486
                        if(session->stack == NULL) {
1487
                                JANUS_LOG(LOG_ERR, "Wrong state (register first)\n");
1488
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1489
                                g_snprintf(error_cause, 512, "Wrong state (register first)");
1490
                                goto error;
1491
                        }
1492
                        if(session->status >= janus_sip_call_status_inviting) {
1493
                                JANUS_LOG(LOG_ERR, "Wrong state (already in a call? status=%s)\n", janus_sip_call_status_string(session->status));
1494
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1495
                                g_snprintf(error_cause, 512, "Wrong state (already in a call? status=%s)", janus_sip_call_status_string(session->status));
1496
                                goto error;
1497
                        }
1498
                        json_t *uri = json_object_get(root, "uri");
1499
                        if(!uri) {
1500
                                JANUS_LOG(LOG_ERR, "Missing element (uri)\n");
1501
                                error_code = JANUS_SIP_ERROR_MISSING_ELEMENT;
1502
                                g_snprintf(error_cause, 512, "Missing element (uri)");
1503
                                goto error;
1504
                        }
1505
                        if(!json_is_string(uri)) {
1506
                                JANUS_LOG(LOG_ERR, "Invalid element (uri should be a string)\n");
1507
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1508
                                g_snprintf(error_cause, 512, "Invalid element (uri should be a string)");
1509
                                goto error;
1510
                        }
1511
                        /* Check if the INVITE needs to be enriched with custom headers */
1512
                        char custom_headers[2048];
1513
                        custom_headers[0] = '\0';
1514
                        json_t *headers = json_object_get(root, "headers");
1515
                        if(headers) {
1516
                                if(!json_is_object(headers)) {
1517
                                        JANUS_LOG(LOG_ERR, "Invalid element (headers should be an object)\n");
1518
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1519
                                        g_snprintf(error_cause, 512, "Invalid element (headers should be an object)");
1520
                                        goto error;
1521
                                }
1522
                                if(json_object_size(headers) > 0) {
1523
                                        /* Parse custom headers */
1524
                                        const char *key = NULL;
1525
                                        json_t *value = NULL;
1526
                                        void *iter = json_object_iter(headers);
1527
                                        while(iter != NULL) {
1528
                                                key = json_object_iter_key(iter);
1529
                                                value = json_object_get(headers, key);
1530
                                                if(value == NULL || !json_is_string(value)) {
1531
                                                        JANUS_LOG(LOG_WARN, "Skipping header '%s': value is not a string\n", key);
1532
                                                        iter = json_object_iter_next(headers, iter);
1533
                                                        continue;
1534
                                                }
1535
                                                char h[255];
1536
                                                g_snprintf(h, 255, "%s: %s\r\n", key, json_string_value(value));
1537
                                                JANUS_LOG(LOG_VERB, "Adding custom header, %s", h);
1538
                                                g_strlcat(custom_headers, h, 2048);
1539
                                                iter = json_object_iter_next(headers, iter);
1540
                                        }
1541
                                }
1542
                        }
1543
                        /* SDES-SRTP is disabled by default, let's see if we need to enable it */
1544
                        gboolean offer_srtp = FALSE, require_srtp = FALSE;
1545
                        json_t *srtp = json_object_get(root, "srtp");
1546
                        if(srtp) {
1547
                                if(!json_is_string(srtp)) {
1548
                                        JANUS_LOG(LOG_ERR, "Invalid element (srtp should be a string)\n");
1549
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1550
                                        g_snprintf(error_cause, 512, "Invalid element (srtp should be a string)");
1551
                                        goto error;
1552
                                }
1553
                                const char *srtp_text = json_string_value(srtp);
1554
                                if(!strcasecmp(srtp_text, "sdes_optional")) {
1555
                                        /* Negotiate SDES, but make it optional */
1556
                                        offer_srtp = TRUE;
1557
                                } else if(!strcasecmp(srtp_text, "sdes_mandatory")) {
1558
                                        /* Negotiate SDES, and require it */
1559
                                        offer_srtp = TRUE;
1560
                                        require_srtp = TRUE;
1561
                                } else {
1562
                                        JANUS_LOG(LOG_ERR, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)\n");
1563
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1564
                                        g_snprintf(error_cause, 512, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)");
1565
                                        goto error;
1566
                                }
1567
                        }
1568
                        /* Parse address */
1569
                        const char *uri_text = json_string_value(uri);
1570
                        janus_sip_uri_t target_uri;
1571
                        if (janus_sip_parse_uri(&target_uri, uri_text) < 0) {
1572
                                JANUS_LOG(LOG_ERR, "Invalid user address %s\n", uri_text);
1573
                                error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1574
                                g_snprintf(error_cause, 512, "Invalid user address %s\n", uri_text);
1575
                                goto error;
1576
                        }
1577
                        /* Any SDP to handle? if not, something's wrong */
1578
                        if(!msg->sdp) {
1579
                                JANUS_LOG(LOG_ERR, "Missing SDP\n");
1580
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1581
                                g_snprintf(error_cause, 512, "Missing SDP");
1582
                                goto error;
1583
                        }
1584
                        JANUS_LOG(LOG_VERB, "%s is calling %s\n", session->account.username, uri_text);
1585
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg->sdp_type, msg->sdp);
1586
                        /* Clean up SRTP stuff from before first, in case it's still needed */
1587
                        janus_sip_srtp_cleanup(session);
1588
                        session->media.require_srtp = require_srtp;
1589
                        session->media.has_srtp_local = offer_srtp;
1590
                        if(offer_srtp) {
1591
                                JANUS_LOG(LOG_VERB, "Going to negotiate SDES-SRTP (%s)...\n", require_srtp ? "mandatory" : "optional");
1592
                        }
1593
                        /* Parse the SDP we got, manipulate some things, and generate a new one */
1594
                        sdp_parser_t *parser = sdp_parse(session->stack->s_home, msg->sdp, strlen(msg->sdp), 0);
1595
                        sdp_session_t *parsed_sdp = sdp_session(parser);
1596
                        if(!parsed_sdp) {
1597
                                JANUS_LOG(LOG_ERR, "Error parsing SDP");
1598
                                sdp_parser_free(parser);
1599
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1600
                                g_snprintf(error_cause, 512, "Error parsing SDP");
1601
                                goto error;
1602
                        }
1603
                        /* Allocate RTP ports and merge them with the anonymized SDP */
1604
                        if(strstr(msg->sdp, "m=audio")) {
1605
                                JANUS_LOG(LOG_VERB, "Going to negotiate audio...\n");
1606
                                session->media.has_audio = 1;        /* FIXME Maybe we need a better way to signal this */
1607
                        }
1608
                        if(strstr(msg->sdp, "m=video")) {
1609
                                JANUS_LOG(LOG_VERB, "Going to negotiate video...\n");
1610
                                session->media.has_video = 1;        /* FIXME Maybe we need a better way to signal this */
1611
                        }
1612
                        if(janus_sip_allocate_local_ports(session) < 0) {
1613
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
1614
                                sdp_parser_free(parser);
1615
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
1616
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
1617
                                goto error;
1618
                        }
1619
                        char *sdp = janus_sip_sdp_manipulate(session, parsed_sdp);
1620
                        if(sdp == NULL) {
1621
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
1622
                                sdp_parser_free(parser);
1623
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
1624
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
1625
                                goto error;
1626
                        }
1627
                        JANUS_LOG(LOG_VERB, "Prepared SDP for INVITE:\n%s", sdp);
1628
                        /* Prepare the stack */
1629
                        if(session->stack->s_nh_i != NULL)
1630
                                nua_handle_destroy(session->stack->s_nh_i);
1631
                        session->stack->s_nh_i = nua_handle(session->stack->s_nua, session, TAG_END());
1632
                        if(session->stack->s_nh_i == NULL) {
1633
                                JANUS_LOG(LOG_WARN, "NUA Handle for INVITE still null??\n");
1634
                                g_free(sdp);
1635
                                sdp_parser_free(parser);
1636
                                error_code = JANUS_SIP_ERROR_LIBSOFIA_ERROR;
1637
                                g_snprintf(error_cause, 512, "Invalid NUA Handle");
1638
                                goto error;
1639
                        }
1640
                        g_atomic_int_set(&session->hangingup, 0);
1641
                        session->status = janus_sip_call_status_inviting;
1642
                        /* Send INVITE */
1643
                        nua_invite(session->stack->s_nh_i,
1644
                                SIPTAG_FROM_STR(session->account.identity),
1645
                                SIPTAG_TO_STR(uri_text),
1646
                                SOATAG_USER_SDP_STR(sdp),
1647
                                NUTAG_PROXY(session->account.proxy),
1648
                                TAG_IF(strlen(custom_headers) > 0, SIPTAG_HEADER_STR(custom_headers)),
1649
                                NUTAG_AUTOANSWER(0),
1650
                                NUTAG_AUTOACK(0),
1651
                                TAG_END());
1652
                        g_free(sdp);
1653
                        sdp_parser_free(parser);
1654
                        session->callee = g_strdup(uri_text);
1655
                        if(session->transaction)
1656
                                g_free(session->transaction);
1657
                        session->transaction = msg->transaction ? g_strdup(msg->transaction) : NULL;
1658
                        /* Send an ack back */
1659
                        result = json_object();
1660
                        json_object_set_new(result, "event", json_string("calling"));
1661
                } else if(!strcasecmp(request_text, "accept")) {
1662
                        if(session->status != janus_sip_call_status_invited) {
1663
                                JANUS_LOG(LOG_ERR, "Wrong state (not invited? status=%s)\n", janus_sip_call_status_string(session->status));
1664
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1665
                                g_snprintf(error_cause, 512, "Wrong state (not invited? status=%s)", janus_sip_call_status_string(session->status));
1666
                                goto error;
1667
                        }
1668
                        if(session->callee == NULL) {
1669
                                JANUS_LOG(LOG_ERR, "Wrong state (no caller?)\n");
1670
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1671
                                g_snprintf(error_cause, 512, "Wrong state (no caller?)");
1672
                                goto error;
1673
                        }
1674
                        json_t *srtp = json_object_get(root, "srtp");
1675
                        gboolean answer_srtp = FALSE;
1676
                        if(srtp) {
1677
                                if(!json_is_string(srtp)) {
1678
                                        JANUS_LOG(LOG_ERR, "Invalid element (srtp should be a string)\n");
1679
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1680
                                        g_snprintf(error_cause, 512, "Invalid element (srtp should be a string)");
1681
                                        goto error;
1682
                                }
1683
                                const char *srtp_text = json_string_value(srtp);
1684
                                if(!strcasecmp(srtp_text, "sdes_optional")) {
1685
                                        /* Negotiate SDES, but make it optional */
1686
                                        answer_srtp = TRUE;
1687
                                } else if(!strcasecmp(srtp_text, "sdes_mandatory")) {
1688
                                        /* Negotiate SDES, and require it */
1689
                                        answer_srtp = TRUE;
1690
                                        session->media.require_srtp = TRUE;
1691
                                } else {
1692
                                        JANUS_LOG(LOG_ERR, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)\n");
1693
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1694
                                        g_snprintf(error_cause, 512, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)");
1695
                                        goto error;
1696
                                }
1697
                        }
1698
                        if(session->media.require_srtp && !session->media.has_srtp_remote) {
1699
                                JANUS_LOG(LOG_ERR, "Can't accept the call: SDES-SRTP required, but caller didn't offer it\n");
1700
                                error_code = JANUS_SIP_ERROR_TOO_STRICT;
1701
                                g_snprintf(error_cause, 512, "Can't accept the call: SDES-SRTP required, but caller didn't offer it");
1702
                                goto error;
1703
                        }
1704
                        answer_srtp = answer_srtp || session->media.has_srtp_remote;
1705
                        /* Any SDP to handle? if not, something's wrong */
1706
                        if(!msg->sdp) {
1707
                                JANUS_LOG(LOG_ERR, "Missing SDP\n");
1708
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1709
                                g_snprintf(error_cause, 512, "Missing SDP");
1710
                                goto error;
1711
                        }
1712
                        /* Accept a call from another peer */
1713
                        JANUS_LOG(LOG_VERB, "We're accepting the call from %s\n", session->callee);
1714
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg->sdp_type, msg->sdp);
1715
                        session->media.has_srtp_local = answer_srtp;
1716
                        if(answer_srtp) {
1717
                                JANUS_LOG(LOG_VERB, "Going to negotiate SDES-SRTP (%s)...\n", session->media.require_srtp ? "mandatory" : "optional");
1718
                        }
1719
                        /* Parse the SDP we got, manipulate some things, and generate a new one */
1720
                        sdp_parser_t *parser = sdp_parse(session->stack->s_home, msg->sdp, strlen(msg->sdp), 0);
1721
                        sdp_session_t *parsed_sdp = sdp_session(parser);
1722
                        if(!parsed_sdp) {
1723
                                JANUS_LOG(LOG_ERR, "Error parsing SDP");
1724
                                sdp_parser_free(parser);
1725
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1726
                                g_snprintf(error_cause, 512, "Error parsing SDP");
1727
                                goto error;
1728
                        }
1729
                        /* Allocate RTP ports and merge them with the anonymized SDP */
1730
                        if(strstr(msg->sdp, "m=audio")) {
1731
                                JANUS_LOG(LOG_VERB, "Going to negotiate audio...\n");
1732
                                session->media.has_audio = 1;        /* FIXME Maybe we need a better way to signal this */
1733
                        }
1734
                        if(strstr(msg->sdp, "m=video")) {
1735
                                JANUS_LOG(LOG_VERB, "Going to negotiate video...\n");
1736
                                session->media.has_video = 1;        /* FIXME Maybe we need a better way to signal this */
1737
                        }
1738
                        if(janus_sip_allocate_local_ports(session) < 0) {
1739
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
1740
                                sdp_parser_free(parser);
1741
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
1742
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
1743
                                goto error;
1744
                        }
1745
                        char *sdp = janus_sip_sdp_manipulate(session, parsed_sdp);
1746
                        if(sdp == NULL) {
1747
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
1748
                                sdp_parser_free(parser);
1749
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
1750
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
1751
                                goto error;
1752
                        }
1753
                        JANUS_LOG(LOG_VERB, "Prepared SDP for 200 OK:\n%s", sdp);
1754
                        /* Send 200 OK */
1755
                        g_atomic_int_set(&session->hangingup, 0);
1756
                        session->status = janus_sip_call_status_incall;
1757
                        if(session->stack->s_nh_i == NULL) {
1758
                                JANUS_LOG(LOG_WARN, "NUA Handle for 200 OK still null??\n");
1759
                        }
1760
                        nua_respond(session->stack->s_nh_i,
1761
                                200, sip_status_phrase(200),
1762
                                SOATAG_USER_SDP_STR(sdp),
1763
                                NUTAG_AUTOANSWER(0),
1764
                                TAG_END());
1765
                        g_free(sdp);
1766
                        sdp_parser_free(parser);
1767
                        /* Send an ack back */
1768
                        result = json_object();
1769
                        json_object_set_new(result, "event", json_string("accepted"));
1770
                        /* Start the media */
1771
                        session->media.ready = 1;        /* FIXME Maybe we need a better way to signal this */
1772
                        GError *error = NULL;
1773
                        g_thread_try_new("janus rtp handler", janus_sip_relay_thread, session, &error);
1774
                        if(error != NULL) {
1775
                                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the RTP/RTCP thread...\n", error->code, error->message ? error->message : "??");
1776
                        }
1777
                } else if(!strcasecmp(request_text, "decline")) {
1778
                        /* Reject an incoming call */
1779
                        if(session->status != janus_sip_call_status_invited) {
1780
                                JANUS_LOG(LOG_ERR, "Wrong state (not invited? status=%s)\n", janus_sip_call_status_string(session->status));
1781
                                /* Ignore */
1782
                                json_decref(root);
1783
                                janus_sip_message_free(msg);
1784
                                continue;
1785
                                //~ g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
1786
                                //~ goto error;
1787
                        }
1788
                        if(session->callee == NULL) {
1789
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
1790
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1791
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
1792
                                goto error;
1793
                        }
1794
                        session->status = janus_sip_call_status_closing;
1795
                        if(session->stack->s_nh_i == NULL) {
1796
                                JANUS_LOG(LOG_WARN, "NUA Handle for 200 OK still null??\n");
1797
                        }
1798
                        int response_code = 486;
1799
                        json_t *code_json = json_object_get(root, "code");
1800
                        if (code_json && json_is_integer(code_json))
1801
                                response_code = json_integer_value(code_json);
1802
                        if (response_code <= 399) {
1803
                                JANUS_LOG(LOG_WARN, "Invalid SIP response code specified, using 486 to decline call\n");
1804
                                response_code = 486;
1805
                        }
1806
                        nua_respond(session->stack->s_nh_i, response_code, sip_status_phrase(response_code), TAG_END());
1807
                        g_free(session->callee);
1808
                        session->callee = NULL;
1809
                        /* Notify the operation */
1810
                        result = json_object();
1811
                        json_object_set_new(result, "event", json_string("declining"));
1812
                        json_object_set_new(result, "code", json_integer(response_code));
1813
                } else if(!strcasecmp(request_text, "hangup")) {
1814
                        /* Hangup an ongoing call */
1815
                        if(!(session->status == janus_sip_call_status_inviting || session->status == janus_sip_call_status_incall)) {
1816
                                JANUS_LOG(LOG_ERR, "Wrong state (not in a call? status=%s)\n", janus_sip_call_status_string(session->status));
1817
                                /* Ignore */
1818
                                json_decref(root);
1819
                                janus_sip_message_free(msg);
1820
                                continue;
1821
                                //~ g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
1822
                                //~ goto error;
1823
                        }
1824
                        if(session->callee == NULL) {
1825
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
1826
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1827
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
1828
                                goto error;
1829
                        }
1830
                        session->status = janus_sip_call_status_closing;
1831
                        nua_bye(session->stack->s_nh_i, TAG_END());
1832
                        g_free(session->callee);
1833
                        session->callee = NULL;
1834
                        /* Notify the operation */
1835
                        result = json_object();
1836
                        json_object_set_new(result, "event", json_string("hangingup"));
1837
                } else if(!strcasecmp(request_text, "recording")) {
1838
                        /* Start or stop recording */
1839
                        if(!(session->status == janus_sip_call_status_inviting || session->status == janus_sip_call_status_incall)) {
1840
                                JANUS_LOG(LOG_ERR, "Wrong state (not in a call? status=%s)\n", janus_sip_call_status_string(session->status));
1841
                                g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
1842
                                goto error;
1843
                        }
1844
                        if(session->callee == NULL) {
1845
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
1846
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1847
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
1848
                                goto error;
1849
                        }
1850
                        json_t *action = json_object_get(root, "action");
1851
                        if(!action) {
1852
                                JANUS_LOG(LOG_ERR, "Missing element (action)\n");
1853
                                error_code = JANUS_SIP_ERROR_MISSING_ELEMENT;
1854
                                g_snprintf(error_cause, 512, "Missing element (action)");
1855
                                goto error;
1856
                        }
1857
                        if(!json_is_string(action)) {
1858
                                JANUS_LOG(LOG_ERR, "Invalid element (action should be a string)\n");
1859
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1860
                                g_snprintf(error_cause, 512, "Invalid element (action should be a string)");
1861
                                goto error;
1862
                        }
1863
                        const char *action_text = json_string_value(action);
1864
                        if(strcasecmp(action_text, "start") && strcasecmp(action_text, "stop")) {
1865
                                JANUS_LOG(LOG_ERR, "Invalid action (should be start|stop)\n");
1866
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1867
                                g_snprintf(error_cause, 512, "Invalid action (should be start|stop)");
1868
                                goto error;
1869
                        }
1870
                        gboolean record_audio = FALSE, record_video = FALSE,        /* No media is recorded by default */
1871
                                record_peer_audio = FALSE, record_peer_video = FALSE;
1872
                        json_t *audio = json_object_get(root, "audio");
1873
                        if(audio && !json_is_boolean(audio)) {
1874
                                JANUS_LOG(LOG_ERR, "Invalid element (audio should be a boolean)\n");
1875
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1876
                                g_snprintf(error_cause, 512, "Invalid value (audio should be a boolean)");
1877
                                goto error;
1878
                        }
1879
                        record_audio = audio ? json_is_true(audio) : FALSE;
1880
                        json_t *video = json_object_get(root, "video");
1881
                        if(video && !json_is_boolean(video)) {
1882
                                JANUS_LOG(LOG_ERR, "Invalid element (video should be a boolean)\n");
1883
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1884
                                g_snprintf(error_cause, 512, "Invalid value (video should be a boolean)");
1885
                                goto error;
1886
                        }
1887
                        record_video = video ? json_is_true(video) : FALSE;
1888
                        json_t *peer_audio = json_object_get(root, "peer_audio");
1889
                        if(peer_audio && !json_is_boolean(peer_audio)) {
1890
                                JANUS_LOG(LOG_ERR, "Invalid element (peer_audio should be a boolean)\n");
1891
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1892
                                g_snprintf(error_cause, 512, "Invalid value (peer_audio should be a boolean)");
1893
                                goto error;
1894
                        }
1895
                        record_peer_audio = peer_audio ? json_is_true(peer_audio) : FALSE;
1896
                        json_t *peer_video = json_object_get(root, "peer_video");
1897
                        if(peer_video && !json_is_boolean(peer_video)) {
1898
                                JANUS_LOG(LOG_ERR, "Invalid element (peer_video should be a boolean)\n");
1899
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1900
                                g_snprintf(error_cause, 512, "Invalid value (peer_video should be a boolean)");
1901
                                goto error;
1902
                        }
1903
                        record_peer_video = peer_video ? json_is_true(peer_video) : FALSE;
1904
                        if(!record_audio && !record_video && !record_peer_audio && !record_peer_video) {
1905
                                JANUS_LOG(LOG_ERR, "Invalid request (at least one of audio, video, peer_audio and peer_video should be true)\n");
1906
                                error_code = JANUS_SIP_ERROR_RECORDING_ERROR;
1907
                                g_snprintf(error_cause, 512, "Invalid request (at least one of audio, video, peer_audio and peer_video should be true)");
1908
                                goto error;
1909
                        }
1910
                        json_t *recfile = json_object_get(root, "filename");
1911
                        if(recfile && !json_is_string(recfile)) {
1912
                                JANUS_LOG(LOG_ERR, "Invalid element (filename should be a string)\n");
1913
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1914
                                g_snprintf(error_cause, 512, "Invalid value (filename should be a string)");
1915
                                goto error;
1916
                        }
1917
                        const char *recording_base = json_string_value(recfile);
1918
                        if(!strcasecmp(action_text, "start")) {
1919
                                /* Start recording something */
1920
                                char filename[255];
1921
                                gint64 now = janus_get_real_time();
1922
                                if(record_peer_audio || record_peer_video) {
1923
                                        JANUS_LOG(LOG_INFO, "Starting recording of peer's %s (user %s, call %s)\n",
1924
                                                (record_peer_audio && record_peer_video ? "audio and video" : (record_peer_audio ? "audio" : "video")),
1925
                                                session->account.username, session->transaction);
1926
                                        /* Start recording this peer's audio and/or video */
1927
                                        if(record_peer_audio) {
1928
                                                memset(filename, 0, 255);
1929
                                                if(recording_base) {
1930
                                                        /* Use the filename and path we have been provided */
1931
                                                        g_snprintf(filename, 255, "%s-peer-audio", recording_base);
1932
                                                        session->arc_peer = janus_recorder_create(NULL, 0, filename);
1933
                                                        if(session->arc_peer == NULL) {
1934
                                                                /* FIXME We should notify the fact the recorder could not be created */
1935
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
1936
                                                        }
1937
                                                } else {
1938
                                                        /* Build a filename */
1939
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-peer-audio",
1940
                                                                session->account.username ? session->account.username : "unknown",
1941
                                                                session->transaction ? session->transaction : "unknown",
1942
                                                                now);
1943
                                                        session->arc_peer = janus_recorder_create(NULL, 0, filename);
1944
                                                        if(session->arc_peer == NULL) {
1945
                                                                /* FIXME We should notify the fact the recorder could not be created */
1946
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
1947
                                                        }
1948
                                                }
1949
                                        }
1950
                                        if(record_peer_video) {
1951
                                                memset(filename, 0, 255);
1952
                                                if(recording_base) {
1953
                                                        /* Use the filename and path we have been provided */
1954
                                                        g_snprintf(filename, 255, "%s-peer-video", recording_base);
1955
                                                        session->vrc_peer = janus_recorder_create(NULL, 1, filename);
1956
                                                        if(session->vrc_peer == NULL) {
1957
                                                                /* FIXME We should notify the fact the recorder could not be created */
1958
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this peer!\n");
1959
                                                        }
1960
                                                } else {
1961
                                                        /* Build a filename */
1962
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-peer-video",
1963
                                                                session->account.username ? session->account.username : "unknown",
1964
                                                                session->transaction ? session->transaction : "unknown",
1965
                                                                now);
1966
                                                        session->vrc_peer = janus_recorder_create(NULL, 1, filename);
1967
                                                        if(session->vrc_peer == NULL) {
1968
                                                                /* FIXME We should notify the fact the recorder could not be created */
1969
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this peer!\n");
1970
                                                        }
1971
                                                }
1972
                                                /* TODO We should send a FIR/PLI to this peer... */
1973
                                        }
1974
                                }
1975
                                if(record_audio || record_video) {
1976
                                        /* Start recording the user's audio and/or video */
1977
                                        JANUS_LOG(LOG_INFO, "Starting recording of user's %s (user %s, call %s)\n",
1978
                                                (record_audio && record_video ? "audio and video" : (record_audio ? "audio" : "video")),
1979
                                                session->account.username, session->transaction);
1980
                                        if(record_audio) {
1981
                                                memset(filename, 0, 255);
1982
                                                if(recording_base) {
1983
                                                        /* Use the filename and path we have been provided */
1984
                                                        g_snprintf(filename, 255, "%s-user-audio", recording_base);
1985
                                                        session->arc = janus_recorder_create(NULL, 0, filename);
1986
                                                        if(session->arc == NULL) {
1987
                                                                /* FIXME We should notify the fact the recorder could not be created */
1988
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
1989
                                                        }
1990
                                                } else {
1991
                                                        /* Build a filename */
1992
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-own-audio",
1993
                                                                session->account.username ? session->account.username : "unknown",
1994
                                                                session->transaction ? session->transaction : "unknown",
1995
                                                                now);
1996
                                                        session->arc = janus_recorder_create(NULL, 0, filename);
1997
                                                        if(session->arc == NULL) {
1998
                                                                /* FIXME We should notify the fact the recorder could not be created */
1999
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
2000
                                                        }
2001
                                                }
2002
                                        }
2003
                                        if(record_video) {
2004
                                                memset(filename, 0, 255);
2005
                                                if(recording_base) {
2006
                                                        /* Use the filename and path we have been provided */
2007
                                                        g_snprintf(filename, 255, "%s-user-video", recording_base);
2008
                                                        session->vrc = janus_recorder_create(NULL, 1, filename);
2009
                                                        if(session->vrc == NULL) {
2010
                                                                /* FIXME We should notify the fact the recorder could not be created */
2011
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this user!\n");
2012
                                                        }
2013
                                                } else {
2014
                                                        /* Build a filename */
2015
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-own-video",
2016
                                                                session->account.username ? session->account.username : "unknown",
2017
                                                                session->transaction ? session->transaction : "unknown",
2018
                                                                now);
2019
                                                        session->vrc = janus_recorder_create(NULL, 1, filename);
2020
                                                        if(session->vrc == NULL) {
2021
                                                                /* FIXME We should notify the fact the recorder could not be created */
2022
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this user!\n");
2023
                                                        }
2024
                                                }
2025
                                                /* Send a PLI */
2026
                                                JANUS_LOG(LOG_VERB, "Recording video, sending a PLI to kickstart it\n");
2027
                                                char buf[12];
2028
                                                memset(buf, 0, 12);
2029
                                                janus_rtcp_pli((char *)&buf, 12);
2030
                                                gateway->relay_rtcp(session->handle, 1, buf, 12);
2031
                                        }
2032
                                }
2033
                        } else {
2034
                                /* Stop recording something: notice that this never returns an error, even when we were not recording anything */
2035
                                if(record_audio) {
2036
                                        if(session->arc) {
2037
                                                janus_recorder_close(session->arc);
2038
                                                JANUS_LOG(LOG_INFO, "Closed user's audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
2039
                                                janus_recorder_free(session->arc);
2040
                                        }
2041
                                        session->arc = NULL;
2042
                                }
2043
                                if(record_video) {
2044
                                        if(session->vrc) {
2045
                                                janus_recorder_close(session->vrc);
2046
                                                JANUS_LOG(LOG_INFO, "Closed user's video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
2047
                                                janus_recorder_free(session->vrc);
2048
                                        }
2049
                                        session->vrc = NULL;
2050
                                }
2051
                                if(record_peer_audio) {
2052
                                        if(session->arc_peer) {
2053
                                                janus_recorder_close(session->arc_peer);
2054
                                                JANUS_LOG(LOG_INFO, "Closed peer's audio recording %s\n", session->arc_peer->filename ? session->arc_peer->filename : "??");
2055
                                                janus_recorder_free(session->arc_peer);
2056
                                        }
2057
                                        session->arc_peer = NULL;
2058
                                }
2059
                                if(record_peer_video) {
2060
                                        if(session->vrc_peer) {
2061
                                                janus_recorder_close(session->vrc_peer);
2062
                                                JANUS_LOG(LOG_INFO, "Closed peer's video recording %s\n", session->vrc_peer->filename ? session->vrc_peer->filename : "??");
2063
                                                janus_recorder_free(session->vrc_peer);
2064
                                        }
2065
                                        session->vrc_peer = NULL;
2066
                                }
2067
                        }
2068
                        /* Notify the result */
2069
                        result = json_object();
2070
                        json_object_set_new(result, "event", json_string("recordingupdated"));
2071
                } else if(!strcasecmp(request_text, "dtmf_info")) {
2072
                        /* Send DMTF tones using SIP INFO
2073
                         * (https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00)
2074
                         */
2075
                        if(!(session->status == janus_sip_call_status_inviting || session->status == janus_sip_call_status_incall)) {
2076
                                JANUS_LOG(LOG_ERR, "Wrong state (not in a call? status=%s)\n", janus_sip_call_status_string(session->status));
2077
                                g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
2078
                                goto error;
2079
                        }
2080
                        if(session->callee == NULL) {
2081
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
2082
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
2083
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
2084
                                goto error;
2085
                        }
2086
                        json_t *digit = json_object_get(root, "digit");
2087
                        if(!digit) {
2088
                                JANUS_LOG(LOG_ERR, "Missing element (digit)\n");
2089
                                error_code = JANUS_SIP_ERROR_MISSING_ELEMENT;
2090
                                g_snprintf(error_cause, 512, "Missing element (digit)");
2091
                                goto error;
2092
                        }
2093
                        if(!json_is_string(digit)) {
2094
                                JANUS_LOG(LOG_ERR, "Invalid element (digit should be a string)\n");
2095
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
2096
                                g_snprintf(error_cause, 512, "Invalid element (digit should be a string)");
2097
                                goto error;
2098
                        }
2099
                        const char *digit_text = json_string_value(digit);
2100
                        if(strlen(digit_text) != 1) {
2101
                                JANUS_LOG(LOG_ERR, "Invalid element (digit should be one character))\n");
2102
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
2103
                                g_snprintf(error_cause, 512, "Invalid element (digit should be one character)");
2104
                                goto error;
2105
                        }
2106
                        int duration_ms = 0;
2107
                        json_t *duration = json_object_get(root, "duration");
2108
                        if(duration && !json_is_integer(duration)) {
2109
                                JANUS_LOG(LOG_ERR, "Invalid element (duration should be an integer)\n");
2110
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
2111
                                g_snprintf(error_cause, 512, "Invalid element (duration should be an integer)");
2112
                                goto error;
2113
                        }
2114
                        duration_ms = duration ? json_integer_value(duration) : 0;
2115
                        if (duration_ms <= 0 || duration_ms > 5000) {
2116
                                duration_ms = 160; /* default value */
2117
                        }
2118

    
2119
                        char payload[64];
2120
                        g_snprintf(payload, sizeof(payload), "Signal=%s\r\nDuration=%d", digit_text, duration_ms);
2121
                        nua_info(session->stack->s_nh_i,
2122
                                SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
2123
                                SIPTAG_PAYLOAD_STR(payload),
2124
                                TAG_END());
2125
                } else {
2126
                        JANUS_LOG(LOG_ERR, "Unknown request (%s)\n", request_text);
2127
                        error_code = JANUS_SIP_ERROR_INVALID_REQUEST;
2128
                        g_snprintf(error_cause, 512, "Unknown request (%s)", request_text);
2129
                        goto error;
2130
                }
2131

    
2132
                json_decref(root);
2133
                /* Prepare JSON event */
2134
                json_t *event = json_object();
2135
                json_object_set_new(event, "sip", json_string("event"));
2136
                if(result != NULL)
2137
                        json_object_set_new(event, "result", result);
2138
                char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2139
                json_decref(event);
2140
                JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
2141
                int ret = gateway->push_event(msg->handle, &janus_sip_plugin, msg->transaction, event_text, sdp_type, sdp);
2142
                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2143
                g_free(event_text);
2144
                if(sdp)
2145
                        g_free(sdp);
2146
                janus_sip_message_free(msg);
2147
                continue;
2148

    
2149
error:
2150
                {
2151
                        if(root != NULL)
2152
                                json_decref(root);
2153
                        /* Prepare JSON error event */
2154
                        json_t *event = json_object();
2155
                        json_object_set_new(event, "sip", json_string("event"));
2156
                        json_object_set_new(event, "error_code", json_integer(error_code));
2157
                        json_object_set_new(event, "error", json_string(error_cause));
2158
                        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2159
                        json_decref(event);
2160
                        JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
2161
                        int ret = gateway->push_event(msg->handle, &janus_sip_plugin, msg->transaction, event_text, NULL, NULL);
2162
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2163
                        g_free(event_text);
2164
                        janus_sip_message_free(msg);
2165
                }
2166
        }
2167
        g_free(error_cause);
2168
        JANUS_LOG(LOG_VERB, "Leaving SIP handler thread\n");
2169
        return NULL;
2170
}
2171

    
2172

    
2173
/* Sofia callbacks */
2174
void janus_sip_sofia_callback(nua_event_t event, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2175
{
2176
        janus_sip_session *session = (janus_sip_session *)magic;
2177
        ssip_t *ssip = session->stack;
2178
        switch (event) {
2179
        /* Status or Error Indications */
2180
                case nua_i_active:
2181
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2182
                        break;
2183
                case nua_i_error:
2184
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2185
                        break;
2186
                case nua_i_fork:
2187
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2188
                        break;
2189
                case nua_i_media_error:
2190
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2191
                        break;
2192
                case nua_i_subscription:
2193
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2194
                        break;
2195
                case nua_i_state:
2196
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2197
                        tagi_t const *ti = tl_find(tags, nutag_callstate);
2198
                        enum nua_callstate callstate = ti ? ti->t_value : -1;
2199
                        /* There are several call states, but we care about the terminated state in order to send the 'hangup' event
2200
                         * and the proceeding state in order to send the 'proceeding' event so the client can play a ringback tone for 
2201
                         * the user since we don't send early media. (assuming this is the right session, of course).
2202
                         * http://sofia-sip.sourceforge.net/refdocs/nua/nua__tag_8h.html#a516dc237722dc8ca4f4aa3524b2b444b
2203
                         */
2204
                        if (callstate == nua_callstate_proceeding && 
2205
                                    (session->stack->s_nh_i == nh || session->stack->s_nh_i == NULL)) {
2206
                                json_t *call = json_object();
2207
                                json_object_set_new(call, "sip", json_string("event"));
2208
                                json_t *calling = json_object();
2209
                                json_object_set_new(calling, "event", json_string("proceeding"));
2210
                                json_object_set_new(calling, "code", json_integer(status));
2211
                                json_object_set_new(call, "result", calling);
2212
                                char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2213
                                json_decref(call);
2214
                                JANUS_LOG(LOG_VERB, "Pushing event: %s\n", call_text);
2215
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call_text, NULL, NULL);
2216
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2217
                                g_free(call_text);
2218
                        } else if(callstate == nua_callstate_terminated &&
2219
                                        (session->stack->s_nh_i == nh || session->stack->s_nh_i == NULL)) {
2220
                                session->status = janus_sip_call_status_idle;
2221
                                session->stack->s_nh_i = NULL;
2222
                                json_t *call = json_object();
2223
                                json_object_set_new(call, "sip", json_string("event"));
2224
                                json_t *calling = json_object();
2225
                                json_object_set_new(calling, "event", json_string("hangup"));
2226
                                json_object_set_new(calling, "code", json_integer(status));
2227
                                json_object_set_new(calling, "reason", json_string(phrase ? phrase : "???"));
2228
                                json_object_set_new(call, "result", calling);
2229
                                char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2230
                                json_decref(call);
2231
                                JANUS_LOG(LOG_VERB, "Pushing event: %s\n", call_text);
2232
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call_text, NULL, NULL);
2233
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2234
                                g_free(call_text);
2235
                                /* Get rid of any PeerConnection that may have been set up */
2236
                                if(session->transaction)
2237
                                        g_free(session->transaction);
2238
                                session->transaction = NULL;
2239
                                gateway->close_pc(session->handle);
2240
                        }
2241
                        break;
2242
                case nua_i_terminated:
2243
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2244
                        break;
2245
        /* SIP requests */
2246
                case nua_i_ack:
2247
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2248
                        break;
2249
                case nua_i_outbound:
2250
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2251
                        break;
2252
                case nua_i_bye: {
2253
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2254
                        break;
2255
                }
2256
                case nua_i_cancel: {
2257
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2258
                        break;
2259
                }
2260
                case nua_i_invite: {
2261
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2262
                        if(ssip == NULL) {
2263
                                JANUS_LOG(LOG_ERR, "\tInvalid SIP stack\n");
2264
                                nua_respond(nh, 500, sip_status_phrase(500), TAG_END());
2265
                                break;
2266
                        }
2267
                        sdp_parser_t *parser = sdp_parse(ssip->s_home, sip->sip_payload->pl_data, sip->sip_payload->pl_len, 0);
2268
                        if(!sdp_session(parser)) {
2269
                                JANUS_LOG(LOG_ERR, "\tError parsing SDP!\n");
2270
                                nua_respond(nh, 488, sip_status_phrase(488), TAG_END());
2271
                                sdp_parser_free(parser);
2272
                                break;
2273
                        }
2274
                        if(session->stack->s_nh_i != NULL) {
2275
                                if(session->stack->s_nh_i == nh) {
2276
                                        /* re-INVITE, we don't support those. */
2277
                                        nua_respond(nh, 488, sip_status_phrase(488), TAG_END());
2278
                                } else if(session->status >= janus_sip_call_status_inviting) {
2279
                                        /* Busy with another call */
2280
                                        JANUS_LOG(LOG_VERB, "\tAlready in a call (busy, status=%s)\n", janus_sip_call_status_string(session->status));
2281
                                        nua_respond(nh, 486, sip_status_phrase(486), TAG_END());
2282
                                        /* Notify the web app about the missed invite */
2283
                                        json_t *missed = json_object();
2284
                                        json_object_set_new(missed, "sip", json_string("event"));
2285
                                        json_t *result = json_object();
2286
                                        json_object_set_new(result, "event", json_string("missed_call"));
2287
                                        char *caller_text = url_as_string(session->stack->s_home, sip->sip_from->a_url);
2288
                                        json_object_set_new(result, "caller", json_string(caller_text));
2289
                                        su_free(session->stack->s_home, caller_text);
2290
                                        if (sip->sip_from && sip->sip_from->a_display) {
2291
                                                json_object_set_new(result, "displayname", json_string(sip->sip_from->a_display));
2292
                                        }
2293
                                        json_object_set_new(missed, "result", result);
2294
                                        char *missed_text = json_dumps(missed, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2295
                                        json_decref(missed);
2296
                                        JANUS_LOG(LOG_VERB, "Pushing event to peer: %s\n", missed_text);
2297
                                        int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, missed_text, NULL, NULL);
2298
                                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2299
                                        g_free(missed_text);
2300
                                }
2301
                                sdp_parser_free(parser);
2302
                                break;
2303
                        }
2304
                        /* New incoming call */
2305
                        session->callee = g_strdup(url_as_string(session->stack->s_home, sip->sip_from->a_url));
2306
                        session->status = janus_sip_call_status_invited;
2307
                        /* Clean up SRTP stuff from before first, in case it's still needed */
2308
                        janus_sip_srtp_cleanup(session);
2309
                        /* Parse SDP */
2310
                        char *fixed_sdp = g_strdup(sip->sip_payload->pl_data);
2311
                        JANUS_LOG(LOG_VERB, "Someone is inviting us in a call:\n%s", sip->sip_payload->pl_data);
2312
                        sdp_session_t *sdp = sdp_session(parser);
2313
                        janus_sip_sdp_process(session, sdp);
2314
                        /* Send SDP to the browser */
2315
                        json_t *call = json_object();
2316
                        json_object_set_new(call, "sip", json_string("event"));
2317
                        json_t *calling = json_object();
2318
                        json_object_set_new(calling, "event", json_string("incomingcall"));
2319
                        json_object_set_new(calling, "username", json_string(session->callee));
2320
                        if(sip->sip_from && sip->sip_from->a_display) {
2321
                                json_object_set_new(calling, "displayname", json_string(sip->sip_from->a_display));
2322
                        }
2323
                        if(session->media.has_srtp_remote) {
2324
                                /* FIXME Maybe a true/false instead? */
2325
                                json_object_set_new(calling, "srtp", json_string(session->media.require_srtp ? "sdes_mandatory" : "sdes_optional"));
2326
                        }
2327
                        json_object_set_new(call, "result", calling);
2328
                        char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2329
                        json_decref(call);
2330
                        JANUS_LOG(LOG_VERB, "Pushing event to peer: %s\n", call_text);
2331
                        int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call_text, "offer", fixed_sdp);
2332
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2333
                        g_free(call_text);
2334
                        g_free(fixed_sdp);
2335
                        /* Send a Ringing back */
2336
                        nua_respond(nh, 180, sip_status_phrase(180), TAG_END());
2337
                        session->stack->s_nh_i = nh;
2338
                        break;
2339
                }
2340
                case nua_i_options:
2341
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2342
                        /* FIXME Should we handle this message? for now we reply with a 405 Method Not Implemented */
2343
                        nua_respond(nh, 405, sip_status_phrase(405), TAG_END());
2344
                        break;
2345
        /* Responses */
2346
                case nua_r_get_params:
2347
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2348
                        break;
2349
                case nua_r_set_params:
2350
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2351
                        break;
2352
                case nua_r_notifier:
2353
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2354
                        break;
2355
                case nua_r_shutdown:
2356
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2357
                        if(status < 200 && !g_atomic_int_get(&stopping)) {
2358
                                /* shutdown in progress -> return */
2359
                                break;
2360
                        }
2361
                        if(ssip != NULL) {
2362
                                /* end the event loop. su_root_run() will return */
2363
                                su_root_break(ssip->s_root);
2364
                        }
2365
                        break;
2366
                case nua_r_terminate:
2367
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2368
                        break;
2369
        /* SIP responses */
2370
                case nua_r_bye:
2371
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2372
                        break;
2373
                case nua_r_cancel:
2374
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2375
                        break;
2376
                case nua_r_info:
2377
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2378
                        break;
2379
                case nua_r_invite: {
2380
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2381
                        
2382
                        if(status < 200) {
2383
                                if (status == 183 || status == 180){
2384
                                        /* SIP/SDP Offer/Answer can get very complex depending on your specific scenario
2385
                                         * This fix for early media considers Use case #1 and #2. Refer to URL below.
2386
                                         * http://sofia-sip.sourceforge.net/refdocs/soa/soa_sdp_oa_use_cases.html
2387
                                         */
2388

    
2389
                                        if(ssip == NULL) {
2390
                                                break;
2391
                                        }
2392
                                        sdp_parser_t *parser = sdp_parse(ssip->s_home, sip->sip_payload->pl_data, sip->sip_payload->pl_len, 0);
2393
                                        if(!sdp_session(parser)) {
2394
                                                sdp_parser_free(parser);
2395
                                                break;
2396
                                        }
2397
                                        
2398
                                        /* Parse SDP */
2399
                                        JANUS_LOG(LOG_VERB, "Sending early media:\n%s", sip->sip_payload->pl_data);
2400
                                        
2401
                                        char *fixed_sdp = g_strdup(sip->sip_payload->pl_data);
2402
                                        sdp_session_t *sdp = sdp_session(parser);
2403
                                        janus_sip_sdp_process(session, sdp);
2404
                                        /* If we asked for SRTP and are not getting it, fail */
2405
                                        if(session->media.require_srtp && !session->media.has_srtp_remote) {
2406
                                                JANUS_LOG(LOG_ERR, "\tWe asked for mandatory SRTP but didn't get any in the reply, ignoring until status 200.\n");
2407
                                                sdp_parser_free(parser);
2408
                                                g_free(fixed_sdp);
2409
                                                break;
2410
                                        }
2411
                                        session->media.ready = 1;        /* FIXME Maybe we need a better way to signal this */
2412
                                        GError *error = NULL;
2413
                                        g_thread_try_new("Early media janus rtp handler", janus_sip_relay_thread, session, &error);
2414
                                        if(error != NULL) {
2415
                                                JANUS_LOG(LOG_ERR, "Early media got error %d (%s) trying to launch the RTP/RTCP thread...\n", error->code, error->message ? error->message : "??");
2416
                                        }
2417
                                        /* Send SDP to the browser */
2418
                                        json_t *call = json_object();
2419
                                        json_object_set_new(call, "sip", json_string("event"));
2420
                                        json_t *calling = json_object();
2421
                                        json_object_set_new(calling, "event", json_string("ringing"));
2422
                                        json_object_set_new(calling, "username", json_string(session->callee));
2423
                                        json_object_set_new(call, "result", calling);
2424
                                        char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2425
                                        json_decref(call);
2426
                                        JANUS_LOG(LOG_VERB, "Early media pushing event to peer: %s\n", call_text);
2427
                                        int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call_text, "answer", fixed_sdp);
2428
                                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2429
                                        g_free(call_text);
2430
                                        g_free(fixed_sdp);
2431
                                }
2432

    
2433
                                break;
2434
                        } else if(status == 401 || status == 407) {
2435
                                char auth[256];
2436
                                const char* scheme;
2437
                                const char* realm;
2438
                                if(status == 401) {
2439
                                         /* Get scheme/realm from 401 error */
2440
                                        sip_www_authenticate_t const* www_auth = sip->sip_www_authenticate;
2441
                                        scheme = www_auth->au_scheme;
2442
                                        realm = msg_params_find(www_auth->au_params, "realm=");
2443
                                } else {
2444
                                         /* Get scheme/realm from 407 error, proxy-auth */
2445
                                        sip_proxy_authenticate_t const* proxy_auth = sip->sip_proxy_authenticate;
2446
                                        scheme = proxy_auth->au_scheme;
2447
                                        realm = msg_params_find(proxy_auth->au_params, "realm=");
2448
                                }
2449
                                memset(auth, 0, sizeof(auth));
2450
                                g_snprintf(auth, sizeof(auth), "%s%s:%s:%s:%s%s",
2451
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
2452
                                        scheme,
2453
                                        realm,
2454
                                        session->account.authuser ? session->account.authuser : "null",
2455
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
2456
                                        session->account.secret ? session->account.secret : "null");
2457
                                JANUS_LOG(LOG_VERB, "\t%s\n", auth);
2458
                                /* Authenticate */
2459
                                nua_authenticate(nh,
2460
                                        NUTAG_AUTH(auth),
2461
                                        TAG_END());
2462
                                break;
2463
                        } else if(status >= 400) {
2464
                                break;
2465
                        }
2466
                        if(ssip == NULL) {
2467
                                JANUS_LOG(LOG_ERR, "\tInvalid SIP stack\n");
2468
                                nua_respond(nh, 500, sip_status_phrase(500), TAG_END());
2469
                                break;
2470
                        }
2471
                        sdp_parser_t *parser = sdp_parse(ssip->s_home, sip->sip_payload->pl_data, sip->sip_payload->pl_len, 0);
2472
                        if(!sdp_session(parser)) {
2473
                                JANUS_LOG(LOG_ERR, "\tError parsing SDP!\n");
2474
                                nua_respond(nh, 488, sip_status_phrase(488), TAG_END());
2475
                                sdp_parser_free(parser);
2476
                                break;
2477
                        }
2478
                        /* Send an ACK */
2479
                        char *route = sip->sip_record_route ? url_as_string(session->stack->s_home, sip->sip_record_route->r_url) : NULL;
2480
                        JANUS_LOG(LOG_WARN, "Sending ACK (route=%s)\n", route ? route : "none");
2481
                        nua_ack(nh,
2482
                                TAG_IF(route, NTATAG_DEFAULT_PROXY(route)),
2483
                                TAG_END());
2484
                        /* Parse SDP */
2485
                        JANUS_LOG(LOG_VERB, "Peer accepted our call:\n%s", sip->sip_payload->pl_data);
2486
                        session->status = janus_sip_call_status_incall;
2487
                        char *fixed_sdp = g_strdup(sip->sip_payload->pl_data);
2488
                        sdp_session_t *sdp = sdp_session(parser);
2489
                        janus_sip_sdp_process(session, sdp);
2490
                        /* If we asked for SRTP and are not getting it, fail */
2491
                        if(session->media.require_srtp && !session->media.has_srtp_remote) {
2492
                                JANUS_LOG(LOG_ERR, "\tWe asked for mandatory SRTP but didn't get any in the reply!\n");
2493
                                sdp_parser_free(parser);
2494
                                g_free(fixed_sdp);
2495
                                /* Hangup immediately */
2496
                                session->status = janus_sip_call_status_closing;
2497
                                nua_bye(nh, TAG_END());
2498
                                g_free(session->callee);
2499
                                session->callee = NULL;
2500
                                break;
2501
                        }
2502
                        session->media.ready = 1;        /* FIXME Maybe we need a better way to signal this */
2503
                        GError *error = NULL;
2504
                        g_thread_try_new("janus rtp handler", janus_sip_relay_thread, session, &error);
2505
                        if(error != NULL) {
2506
                                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the RTP/RTCP thread...\n", error->code, error->message ? error->message : "??");
2507
                        }
2508
                        /* Send SDP to the browser */
2509
                        json_t *call = json_object();
2510
                        json_object_set_new(call, "sip", json_string("event"));
2511
                        json_t *calling = json_object();
2512
                        json_object_set_new(calling, "event", json_string("accepted"));
2513
                        json_object_set_new(calling, "username", json_string(session->callee));
2514
                        json_object_set_new(call, "result", calling);
2515
                        char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2516
                        json_decref(call);
2517
                        JANUS_LOG(LOG_VERB, "Pushing event to peer: %s\n", call_text);
2518
                        int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call_text, "answer", fixed_sdp);
2519
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2520
                        g_free(call_text);
2521
                        g_free(fixed_sdp);
2522
                        break;
2523
                }
2524
                case nua_r_register: {
2525
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2526
                        if(status == 200) {
2527
                                if(session->account.registration_status < janus_sip_registration_status_registered)
2528
                                        session->account.registration_status = janus_sip_registration_status_registered;
2529
                                JANUS_LOG(LOG_VERB, "Successfully registered\n");
2530
                                /* Notify the browser */
2531
                                json_t *call = json_object();
2532
                                json_object_set_new(call, "sip", json_string("event"));
2533
                                json_t *calling = json_object();
2534
                                json_object_set_new(calling, "event", json_string("registered"));
2535
                                json_object_set_new(calling, "username", json_string(session->account.username));
2536
                                json_object_set_new(calling, "register_sent", json_string("true"));
2537
                                json_object_set_new(call, "result", calling);
2538
                                char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2539
                                json_decref(call);
2540
                                JANUS_LOG(LOG_VERB, "Pushing event: %s\n", call_text);
2541
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call_text, NULL, NULL);
2542
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2543
                                g_free(call_text);
2544
                        } else if(status == 401) {
2545
                                /* Get scheme/realm from 401 error */
2546
                                sip_www_authenticate_t const* www_auth = sip->sip_www_authenticate;
2547
                                char const* scheme = www_auth->au_scheme;
2548
                                const char* realm = msg_params_find(www_auth->au_params, "realm=");
2549
                                char auth[256];
2550
                                memset(auth, 0, sizeof(auth));
2551
                                g_snprintf(auth, sizeof(auth), "%s%s:%s:%s:%s%s",
2552
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
2553
                                        scheme,
2554
                                        realm,
2555
                                        session->account.authuser ? session->account.authuser : "null",
2556
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
2557
                                        session->account.secret);
2558
                                JANUS_LOG(LOG_VERB, "\t%s\n", auth);
2559
                                /* Authenticate */
2560
                                nua_authenticate(nh,
2561
                                        NUTAG_AUTH(auth),
2562
                                        TAG_END());
2563
                        } else if(status >= 400) {
2564
                                /* Authentication failed? */
2565
                                session->account.registration_status = janus_sip_registration_status_failed;
2566
                                /* Tell the browser... */
2567
                                json_t *event = json_object();
2568
                                json_object_set_new(event, "sip", json_string("event"));
2569
                                json_t *result = json_object();
2570
                                json_object_set_new(result, "event", json_string("registration_failed"));
2571
                                json_object_set_new(result, "code", json_integer(status));
2572
                                json_object_set_new(result, "reason", json_string(phrase ? phrase : ""));
2573
                                json_object_set_new(event, "result", result);
2574
                                char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2575
                                json_decref(event);
2576
                                JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
2577
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, event_text, NULL, NULL);
2578
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2579
                                g_free(event_text);
2580
                        }
2581
                        break;
2582
                }
2583
                default:
2584
                        /* unknown event -> print out error message */
2585
                        JANUS_LOG(LOG_ERR, "Unknown event %d (%s)\n", event, nua_event_name(event));
2586
                        break;
2587
        }
2588
}
2589

    
2590
void janus_sip_sdp_process(janus_sip_session *session, sdp_session_t *sdp) {
2591
        if(!session || !sdp)
2592
                return;
2593
        /* c= */
2594
        if(sdp->sdp_connection && sdp->sdp_connection->c_address) {
2595
                g_free(session->media.remote_ip);
2596
                session->media.remote_ip = g_strdup(sdp->sdp_connection->c_address);
2597
                JANUS_LOG(LOG_VERB, "  >> Media connection:\n");
2598
                JANUS_LOG(LOG_VERB, "       %s\n", session->media.remote_ip);
2599
        }
2600
        JANUS_LOG(LOG_VERB, "  >> Media lines:\n");
2601
        sdp_media_t *m = sdp->sdp_media;
2602
        while(m) {
2603
                session->media.require_srtp = session->media.require_srtp || (m->m_proto_name && !strcasecmp(m->m_proto_name, "RTP/SAVP"));
2604
                if(m->m_type == sdp_media_audio) {
2605
                        JANUS_LOG(LOG_VERB, "       Audio: %lu\n", m->m_port);
2606
                        if(m->m_port) {
2607
                                session->media.has_audio = 1;
2608
                                session->media.remote_audio_rtp_port = m->m_port;
2609
                                session->media.remote_audio_rtcp_port = m->m_port+1;        /* FIXME We're assuming RTCP is on the next port */
2610
                        }
2611
                } else if(m->m_type == sdp_media_video) {
2612
                        JANUS_LOG(LOG_VERB, "       Video: %lu\n", m->m_port);
2613
                        if(m->m_port) {
2614
                                session->media.has_video = 1;
2615
                                session->media.remote_video_rtp_port = m->m_port;
2616
                                session->media.remote_video_rtcp_port = m->m_port+1;        /* FIXME We're assuming RTCP is on the next port */
2617
                        }
2618
                } else {
2619
                        JANUS_LOG(LOG_WARN, "       Unsupported media line (not audio/video)\n");
2620
                        m = m->m_next;
2621
                        continue;
2622
                }
2623
                JANUS_LOG(LOG_VERB, "       Media connections:\n");
2624
                if(m->m_connections) {
2625
                        sdp_connection_t *c = m->m_connections;
2626
                        while(c) {
2627
                                if(c->c_address) {
2628
                                        g_free(session->media.remote_ip);
2629
                                        session->media.remote_ip = g_strdup(c->c_address);
2630
                                        JANUS_LOG(LOG_VERB, "         [%s]\n", session->media.remote_ip);
2631
                                }
2632
                                c = c->c_next;
2633
                        }
2634
                }
2635
                JANUS_LOG(LOG_VERB, "       Media RTP maps:\n");
2636
                sdp_rtpmap_t *r = m->m_rtpmaps;
2637
                while(r) {
2638
                        JANUS_LOG(LOG_VERB, "         [%u] %s\n", r->rm_pt, r->rm_encoding);
2639
                        r = r->rm_next;
2640
                }
2641
                JANUS_LOG(LOG_VERB, "       Media attributes:\n");
2642
                sdp_attribute_t *a = m->m_attributes;
2643
                while(a) {
2644
                        if(a->a_name) {
2645
                                if(!strcasecmp(a->a_name, "rtpmap")) {
2646
                                        JANUS_LOG(LOG_VERB, "         RTP Map:     %s\n", a->a_value);
2647
                                } else if(!strcasecmp(a->a_name, "crypto")) {
2648
                                        JANUS_LOG(LOG_VERB, "         Crypto:      %s\n", a->a_value);
2649
                                        if(m->m_type == sdp_media_audio || m->m_type == sdp_media_video) {
2650
                                                gint32 tag = 0;
2651
                                                int suite;
2652
                                                char crypto[40];
2653
                                                /* FIXME inline can be more complex than that, and we're currently only offering SHA1_80 */
2654
                                                int res = sscanf(a->a_value, "%"SCNi32" AES_CM_128_HMAC_SHA1_%2d inline:%40s",
2655
                                                        &tag, &suite, crypto);
2656
                                                if(res != 3) {
2657
                                                        JANUS_LOG(LOG_WARN, "Failed to parse crypto line, ignoring... %s\n", a->a_value);
2658
                                                } else {
2659
                                                        gboolean video = (m->m_type == sdp_media_video);
2660
                                                        int current_suite = video ? session->media.video_srtp_suite_in : session->media.audio_srtp_suite_in;
2661
                                                        if(current_suite == 0) {
2662
                                                                if(video)
2663
                                                                        session->media.video_srtp_suite_in = suite;
2664
                                                                else
2665
                                                                        session->media.audio_srtp_suite_in = suite;
2666
                                                                janus_sip_srtp_set_remote(session, video, crypto, suite);
2667
                                                                session->media.has_srtp_remote = TRUE;
2668
                                                        } else {
2669
                                                                JANUS_LOG(LOG_WARN, "We already configured a %s crypto context (AES_CM_128_HMAC_SHA1_%d), skipping additional crypto line\n",
2670
                                                                        video ? "video" : "audio", current_suite);
2671
                                                        }
2672
                                                }
2673
                                        }
2674
                                }
2675
                        }
2676
                        a = a->a_next;
2677
                }
2678
                m = m->m_next;
2679
        }
2680
}
2681

    
2682
char *janus_sip_sdp_manipulate(janus_sip_session *session, sdp_session_t *sdp) {
2683
        if(!session || !session->stack || !sdp)
2684
                return NULL;
2685
        /* Placeholders for later */
2686
        sdp_attribute_t crypto_audio = {
2687
                .a_size = sizeof(sdp_attribute_t),
2688
                .a_name = "crypto",
2689
                .a_value = "audio"
2690
        };
2691
        sdp_attribute_t crypto_video = {
2692
                .a_size = sizeof(sdp_attribute_t),
2693
                .a_name = "crypto",
2694
                .a_value = "video"
2695
        };
2696
        /* Start replacing stuff */
2697
        if(sdp->sdp_connection && sdp->sdp_connection->c_address) {
2698
                sdp->sdp_connection->c_address = local_ip;
2699
        }
2700
        JANUS_LOG(LOG_VERB, "Setting protocol to %s\n", session->media.require_srtp ? "RTP/SAVP" : "RTP/AVP");
2701
        sdp_media_t *m = sdp->sdp_media;
2702
        while(m) {
2703
                m->m_proto = session->media.require_srtp ? sdp_proto_srtp : sdp_proto_rtp;
2704
                m->m_proto_name = session->media.require_srtp ? "RTP/SAVP" : "RTP/AVP";
2705
                if(m->m_type == sdp_media_audio) {
2706
                        m->m_port = session->media.local_audio_rtp_port;
2707
                        if(session->media.has_srtp_local) {
2708
                                sdp_attribute_append(&m->m_attributes, &crypto_audio);
2709
                        }
2710
                } else if(m->m_type == sdp_media_video) {
2711
                        m->m_port = session->media.local_video_rtp_port;
2712
                        if(session->media.has_srtp_local) {
2713
                                sdp_attribute_append(&m->m_attributes, &crypto_video);
2714
                        }
2715
                }
2716
                if(m->m_connections) {
2717
                        sdp_connection_t *c = m->m_connections;
2718
                        while(c) {
2719
                                c->c_address = local_ip;
2720
                                c = c->c_next;
2721
                        }
2722
                }
2723
                m = m->m_next;
2724
        }
2725
        /* Generate a SDP string out of our changes */
2726
        char buf[2048];
2727
        sdp_printer_t *printer = sdp_print(session->stack->s_home, sdp, buf, 2048, 0);
2728
        if(!sdp_message(printer)) {
2729
                sdp_printer_free(printer);
2730
                return NULL;
2731
        }
2732
        sdp_printer_free(printer);
2733
        char *new_sdp = g_strdup(buf);
2734
        /* If any crypto placeholer was there, fix that */
2735
        if(session->media.has_srtp_local) {
2736
                if(session->media.has_audio) {
2737
                        char *crypto = NULL;
2738
                        session->media.audio_srtp_suite_out = 80;
2739
                        janus_sip_srtp_set_local(session, FALSE, &crypto);
2740
                        /* FIXME 32? 80? Both? */
2741
                        char cryptoline[100];
2742
                        g_snprintf(cryptoline, 100, "a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:%s", crypto);
2743
                        g_free(crypto);
2744
                        new_sdp = janus_string_replace(new_sdp, "a=crypto:audio", cryptoline);
2745
                }
2746
                if(session->media.has_video) {
2747
                        char *crypto = NULL;
2748
                        session->media.video_srtp_suite_out = 80;
2749
                        janus_sip_srtp_set_local(session, TRUE, &crypto);
2750
                        /* FIXME 32? 80? Both? */
2751
                        char cryptoline[100];
2752
                        g_snprintf(cryptoline, 100, "a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:%s", crypto);
2753
                        g_free(crypto);
2754
                        new_sdp = janus_string_replace(new_sdp, "a=crypto:video", cryptoline);
2755
                }
2756
        }
2757
        return new_sdp;
2758
}
2759

    
2760
/* Bind local RTP/RTCP sockets */
2761
static int janus_sip_allocate_local_ports(janus_sip_session *session) {
2762
        if(session == NULL) {
2763
                JANUS_LOG(LOG_ERR, "Invalid session\n");
2764
                return -1;
2765
        }
2766
        /* Reset status */
2767
        if(session->media.audio_rtp_fd != -1) {
2768
                close(session->media.audio_rtp_fd);
2769
                session->media.audio_rtp_fd = -1;
2770
        }
2771
        if(session->media.audio_rtcp_fd != -1) {
2772
                close(session->media.audio_rtcp_fd);
2773
                session->media.audio_rtcp_fd = -1;
2774
        }
2775
        session->media.local_audio_rtp_port = 0;
2776
        session->media.local_audio_rtcp_port = 0;
2777
        session->media.audio_ssrc = 0;
2778
        if(session->media.video_rtp_fd != -1) {
2779
                close(session->media.video_rtp_fd);
2780
                session->media.video_rtp_fd = -1;
2781
        }
2782
        if(session->media.video_rtcp_fd != -1) {
2783
                close(session->media.video_rtcp_fd);
2784
                session->media.video_rtcp_fd = -1;
2785
        }
2786
        session->media.local_video_rtp_port = 0;
2787
        session->media.local_video_rtcp_port = 0;
2788
        session->media.video_ssrc = 0;
2789
        /* Start */
2790
        int attempts = 100;        /* FIXME Don't retry forever */
2791
        if(session->media.has_audio) {
2792
                JANUS_LOG(LOG_VERB, "Allocating audio ports:\n");
2793
                struct sockaddr_in audio_rtp_address, audio_rtcp_address;
2794
                while(session->media.local_audio_rtp_port == 0 || session->media.local_audio_rtcp_port == 0) {
2795
                        if(attempts == 0)        /* Too many failures */
2796
                                return -1;
2797
                        if(session->media.audio_rtp_fd == -1) {
2798
                                session->media.audio_rtp_fd = socket(AF_INET, SOCK_DGRAM, 0);
2799
                        }
2800
                        if(session->media.audio_rtcp_fd == -1) {
2801
                                session->media.audio_rtcp_fd = socket(AF_INET, SOCK_DGRAM, 0);
2802
                        }
2803
                        int rtp_port = g_random_int_range(10000, 60000);        /* FIXME Should this be configurable? */
2804
                        if(rtp_port % 2)
2805
                                rtp_port++;        /* Pick an even port for RTP */
2806
                        audio_rtp_address.sin_family = AF_INET;
2807
                        audio_rtp_address.sin_port = htons(rtp_port);
2808
                        inet_pton(AF_INET, local_ip, &audio_rtp_address.sin_addr.s_addr);
2809
                        if(bind(session->media.audio_rtp_fd, (struct sockaddr *)(&audio_rtp_address), sizeof(struct sockaddr)) < 0) {
2810
                                JANUS_LOG(LOG_ERR, "Bind failed for audio RTP (port %d), trying a different one...\n", rtp_port);
2811
                                attempts--;
2812
                                continue;
2813
                        }
2814
                        JANUS_LOG(LOG_VERB, "Audio RTP listener bound to port %d\n", rtp_port);
2815
                        int rtcp_port = rtp_port+1;
2816
                        audio_rtcp_address.sin_family = AF_INET;
2817
                        audio_rtcp_address.sin_port = htons(rtcp_port);
2818
                        inet_pton(AF_INET, local_ip, &audio_rtcp_address.sin_addr.s_addr);
2819
                        if(bind(session->media.audio_rtcp_fd, (struct sockaddr *)(&audio_rtcp_address), sizeof(struct sockaddr)) < 0) {
2820
                                JANUS_LOG(LOG_ERR, "Bind failed for audio RTCP (port %d), trying a different one...\n", rtcp_port);
2821
                                /* RTP socket is not valid anymore, reset it */
2822
                                close(session->media.audio_rtp_fd);
2823
                                session->media.audio_rtp_fd = -1;
2824
                                attempts--;
2825
                                continue;
2826
                        }
2827
                        JANUS_LOG(LOG_VERB, "Audio RTCP listener bound to port %d\n", rtcp_port);
2828
                        session->media.local_audio_rtp_port = rtp_port;
2829
                        session->media.local_audio_rtcp_port = rtcp_port;
2830
                }
2831
        }
2832
        if(session->media.has_video) {
2833
                JANUS_LOG(LOG_VERB, "Allocating video ports:\n");
2834
                struct sockaddr_in video_rtp_address, video_rtcp_address;
2835
                while(session->media.local_video_rtp_port == 0 || session->media.local_video_rtcp_port == 0) {
2836
                        if(attempts == 0)        /* Too many failures */
2837
                                return -1;
2838
                        if(session->media.video_rtp_fd == -1) {
2839
                                session->media.video_rtp_fd = socket(AF_INET, SOCK_DGRAM, 0);
2840
                        }
2841
                        if(session->media.video_rtcp_fd == -1) {
2842
                                session->media.video_rtcp_fd = socket(AF_INET, SOCK_DGRAM, 0);
2843
                        }
2844
                        int rtp_port = g_random_int_range(10000, 60000);        /* FIXME Should this be configurable? */
2845
                        if(rtp_port % 2)
2846
                                rtp_port++;        /* Pick an even port for RTP */
2847
                        video_rtp_address.sin_family = AF_INET;
2848
                        video_rtp_address.sin_port = htons(rtp_port);
2849
                        inet_pton(AF_INET, local_ip, &video_rtp_address.sin_addr.s_addr);
2850
                        if(bind(session->media.video_rtp_fd, (struct sockaddr *)(&video_rtp_address), sizeof(struct sockaddr)) < 0) {
2851
                                JANUS_LOG(LOG_ERR, "Bind failed for video RTP (port %d), trying a different one...\n", rtp_port);
2852
                                attempts--;
2853
                                continue;
2854
                        }
2855
                        JANUS_LOG(LOG_VERB, "Video RTP listener bound to port %d\n", rtp_port);
2856
                        int rtcp_port = rtp_port+1;
2857
                        video_rtcp_address.sin_family = AF_INET;
2858
                        video_rtcp_address.sin_port = htons(rtcp_port);
2859
                        inet_pton(AF_INET, local_ip, &video_rtcp_address.sin_addr.s_addr);
2860
                        if(bind(session->media.video_rtcp_fd, (struct sockaddr *)(&video_rtcp_address), sizeof(struct sockaddr)) < 0) {
2861
                                JANUS_LOG(LOG_ERR, "Bind failed for video RTCP (port %d), trying a different one...\n", rtcp_port);
2862
                                /* RTP socket is not valid anymore, reset it */
2863
                                close(session->media.video_rtp_fd);
2864
                                session->media.video_rtp_fd = -1;
2865
                                attempts--;
2866
                                continue;
2867
                        }
2868
                        JANUS_LOG(LOG_VERB, "Video RTCP listener bound to port %d\n", rtcp_port);
2869
                        session->media.local_video_rtp_port = rtp_port;
2870
                        session->media.local_video_rtcp_port = rtcp_port;
2871
                }
2872
        }
2873
        return 0;
2874
}
2875

    
2876
/* Thread to relay RTP/RTCP frames coming from the SIP peer */
2877
static void *janus_sip_relay_thread(void *data) {
2878
        janus_sip_session *session = (janus_sip_session *)data;
2879
        if(!session || !session->account.username || !session->callee) {
2880
                g_thread_unref(g_thread_self());
2881
                return NULL;
2882
        }
2883
        JANUS_LOG(LOG_VERB, "Starting relay thread (%s <--> %s)\n", session->account.username, session->callee);
2884

    
2885
        gboolean have_server_ip = TRUE;
2886
        struct sockaddr_in server_addr;
2887
        memset(&server_addr, 0, sizeof(server_addr));
2888
        server_addr.sin_family = AF_INET;
2889
        if((inet_aton(session->media.remote_ip, &server_addr.sin_addr)) <= 0) {        /* Not a numeric IP... */
2890
                struct hostent *host = gethostbyname(session->media.remote_ip);        /* ...resolve name */
2891
                if(!host) {
2892
                        JANUS_LOG(LOG_ERR, "[SIP-%s] Couldn't get host (%s)\n", session->account.username, session->media.remote_ip);
2893
                        have_server_ip = FALSE;
2894
                } else {
2895
                        server_addr.sin_addr = *(struct in_addr *)host->h_addr_list;
2896
                }
2897
        }
2898

    
2899
        /* Connect peers (FIXME This pretty much sucks right now) */
2900
        if(have_server_ip && session->media.remote_audio_rtp_port) {
2901
                server_addr.sin_port = htons(session->media.remote_audio_rtp_port);
2902
                if(connect(session->media.audio_rtp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2903
                        JANUS_LOG(LOG_ERR, "[SIP-%s] Couldn't connect audio RTP? (%s:%d)\n", session->account.username, session->media.remote_ip, session->media.remote_audio_rtp_port);
2904
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2905
                }
2906
        }
2907
        if(have_server_ip && session->media.remote_audio_rtcp_port) {
2908
                server_addr.sin_port = htons(session->media.remote_audio_rtcp_port);
2909
                if(connect(session->media.audio_rtcp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2910
                        JANUS_LOG(LOG_ERR, "[SIP-%s] Couldn't connect audio RTCP? (%s:%d)\n", session->account.username, session->media.remote_ip, session->media.remote_audio_rtcp_port);
2911
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2912
                }
2913
        }
2914
        if(have_server_ip && session->media.remote_video_rtp_port) {
2915
                server_addr.sin_port = htons(session->media.remote_video_rtp_port);
2916
                if(connect(session->media.video_rtp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2917
                        JANUS_LOG(LOG_ERR, "[SIP-%s] Couldn't connect video RTP? (%s:%d)\n", session->account.username, session->media.remote_ip, session->media.remote_video_rtp_port);
2918
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2919
                }
2920
        }
2921
        if(have_server_ip && session->media.remote_video_rtcp_port) {
2922
                server_addr.sin_port = htons(session->media.remote_video_rtcp_port);
2923
                if(connect(session->media.video_rtcp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2924
                        JANUS_LOG(LOG_ERR, "[SIP-%s] Couldn't connect video RTCP? (%s:%d)\n", session->account.username, session->media.remote_ip, session->media.remote_video_rtcp_port);
2925
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2926
                }
2927
        }
2928

    
2929
        if(!session->callee) {
2930
                JANUS_LOG(LOG_VERB, "[SIP-%s] Leaving thread, no callee...\n", session->account.username);
2931
                g_thread_unref(g_thread_self());
2932
                return NULL;
2933
        }
2934
        /* File descriptors */
2935
        socklen_t addrlen;
2936
        struct sockaddr_in remote;
2937
        int resfd = 0, bytes = 0;
2938
        struct pollfd fds[4];
2939
        char buffer[1500];
2940
        memset(buffer, 0, 1500);
2941
        /* Loop */
2942
        int num = 0;
2943
        gboolean goon = TRUE;
2944
        while(goon && session != NULL && !session->destroyed &&
2945
                        session->status > janus_sip_call_status_idle &&
2946
                        session->status < janus_sip_call_status_closing) {        /* FIXME We need a per-call watchdog as well */
2947
                /* Prepare poll */
2948
                num = 0;
2949
                if(session->media.audio_rtp_fd != -1) {
2950
                        fds[num].fd = session->media.audio_rtp_fd;
2951
                        fds[num].events = POLLIN;
2952
                        fds[num].revents = 0;
2953
                        num++;
2954
                }
2955
                if(session->media.audio_rtcp_fd != -1) {
2956
                        fds[num].fd = session->media.audio_rtcp_fd;
2957
                        fds[num].events = POLLIN;
2958
                        fds[num].revents = 0;
2959
                        num++;
2960
                }
2961
                if(session->media.video_rtp_fd != -1) {
2962
                        fds[num].fd = session->media.video_rtp_fd;
2963
                        fds[num].events = POLLIN;
2964
                        fds[num].revents = 0;
2965
                        num++;
2966
                }
2967
                if(session->media.video_rtcp_fd != -1) {
2968
                        fds[num].fd = session->media.video_rtcp_fd;
2969
                        fds[num].events = POLLIN;
2970
                        fds[num].revents = 0;
2971
                        num++;
2972
                }
2973
                /* Wait for some data */
2974
                resfd = poll(fds, num, 1000);
2975
                if(resfd < 0) {
2976
                        JANUS_LOG(LOG_ERR, "[SIP-%s] Error polling...\n", session->account.username);
2977
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2978
                        break;
2979
                } else if(resfd == 0) {
2980
                        /* No data, keep going */
2981
                        continue;
2982
                }
2983
                if(session == NULL || session->destroyed ||
2984
                                session->status <= janus_sip_call_status_idle ||
2985
                                session->status >= janus_sip_call_status_closing)
2986
                        break;
2987
                int i = 0;
2988
                for(i=0; i<num; i++) {
2989
                        if(fds[i].revents & (POLLERR | POLLHUP)) {
2990
                                /* Socket error? */
2991
                                JANUS_LOG(LOG_ERR, "[SIP-%s] Error polling: %s...\n", session->account.username,
2992
                                        fds[i].revents & POLLERR ? "POLLERR" : "POLLHUP");
2993
                                JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2994
                                goon = FALSE;        /* Can we assume it's pretty much over, after a POLLERR? */
2995
                                /* FIXME Simulate a "hangup" coming from the browser */
2996
                                janus_sip_message *msg = g_malloc0(sizeof(janus_sip_message));
2997
                                msg->handle = session->handle;
2998
                                msg->message = g_strdup("{\"request\":\"hangup\"}");
2999
                                msg->transaction = NULL;
3000
                                msg->sdp_type = NULL;
3001
                                msg->sdp = NULL;
3002
                                g_async_queue_push(messages, msg);
3003
                                break;
3004
                        } else if(fds[i].revents & POLLIN) {
3005
                                /* Got an RTP/RTCP packet */
3006
                                if(session->media.audio_rtp_fd != -1 && fds[i].fd == session->media.audio_rtp_fd) {
3007
                                        /* Got something audio (RTP) */
3008
                                        addrlen = sizeof(remote);
3009
                                        bytes = recvfrom(session->media.audio_rtp_fd, buffer, 1500, 0, (struct sockaddr*)&remote, &addrlen);
3010
                                        //~ JANUS_LOG(LOG_VERB, "************************\nGot %d bytes on the audio RTP channel...\n", bytes);
3011
                                        //~ rtp_header_t *rtp = (rtp_header_t *)buffer;
3012
                                        //~ JANUS_LOG(LOG_VERB, " ... parsed RTP packet (ssrc=%u, pt=%u, seq=%u, ts=%u)...\n",
3013
                                                //~ ntohl(rtp->ssrc), rtp->type, ntohs(rtp->seq_number), ntohl(rtp->timestamp));
3014
                                        if(session->media.audio_ssrc_peer == 0) {
3015
                                                rtp_header *header = (rtp_header *)buffer;
3016
                                                session->media.audio_ssrc_peer = ntohl(header->ssrc);
3017
                                                JANUS_LOG(LOG_VERB, "Got SIP peer audio SSRC: %"SCNu32"\n", session->media.audio_ssrc_peer);
3018
                                        }
3019
                                        /* Is this SRTP? */
3020
                                        if(session->media.has_srtp_remote) {
3021
                                                int buflen = bytes;
3022
                                                err_status_t res = srtp_unprotect(session->media.audio_srtp_in, buffer, &buflen);
3023
                                                if(res != err_status_ok && res != err_status_replay_fail && res != err_status_replay_old) {
3024
                                                        rtp_header *header = (rtp_header *)buffer;
3025
                                                        guint32 timestamp = ntohl(header->timestamp);
3026
                                                        guint16 seq = ntohs(header->seq_number);
3027
                                                        JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTP unprotect error: %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")\n",
3028
                                                                session->account.username, janus_sip_get_srtp_error(res), bytes, buflen, timestamp, seq);
3029
                                                        continue;
3030
                                                }
3031
                                                bytes = buflen;
3032
                                        }
3033
                                        /* Save the frame if we're recording */
3034
                                        if(session->arc_peer)
3035
                                                janus_recorder_save_frame(session->arc_peer, buffer, bytes);
3036
                                        /* Relay to browser */
3037
                                        gateway->relay_rtp(session->handle, 0, buffer, bytes);
3038
                                        continue;
3039
                                } else if(session->media.audio_rtcp_fd != -1 && fds[i].fd == session->media.audio_rtcp_fd) {
3040
                                        /* Got something audio (RTCP) */
3041
                                        addrlen = sizeof(remote);
3042
                                        bytes = recvfrom(session->media.audio_rtcp_fd, buffer, 1500, 0, (struct sockaddr*)&remote, &addrlen);
3043
                                        //~ JANUS_LOG(LOG_VERB, "************************\nGot %d bytes on the audio RTCP channel...\n", bytes);
3044
                                        /* Is this SRTCP? */
3045
                                        if(session->media.has_srtp_remote) {
3046
                                                int buflen = bytes;
3047
                                                err_status_t res = srtp_unprotect_rtcp(session->media.audio_srtp_in, buffer, &buflen);
3048
                                                if(res != err_status_ok && res != err_status_replay_fail && res != err_status_replay_old) {
3049
                                                        JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTCP unprotect error: %s (len=%d-->%d)\n",
3050
                                                                session->account.username, janus_sip_get_srtp_error(res), bytes, buflen);
3051
                                                        continue;
3052
                                                }
3053
                                                bytes = buflen;
3054
                                        }
3055
                                        /* Relay to browser */
3056
                                        gateway->relay_rtcp(session->handle, 0, buffer, bytes);
3057
                                        continue;
3058
                                } else if(session->media.video_rtp_fd != -1 && fds[i].fd == session->media.video_rtp_fd) {
3059
                                        /* Got something video (RTP) */
3060
                                        addrlen = sizeof(remote);
3061
                                        bytes = recvfrom(session->media.video_rtp_fd, buffer, 1500, 0, (struct sockaddr*)&remote, &addrlen);
3062
                                        //~ JANUS_LOG(LOG_VERB, "************************\nGot %d bytes on the video RTP channel...\n", bytes);
3063
                                        //~ rtp_header_t *rtp = (rtp_header_t *)buffer;
3064
                                        //~ JANUS_LOG(LOG_VERB, " ... parsed RTP packet (ssrc=%u, pt=%u, seq=%u, ts=%u)...\n",
3065
                                                //~ ntohl(rtp->ssrc), rtp->type, ntohs(rtp->seq_number), ntohl(rtp->timestamp));
3066
                                        if(session->media.video_ssrc_peer == 0) {
3067
                                                rtp_header *header = (rtp_header *)buffer;
3068
                                                session->media.video_ssrc_peer = ntohl(header->ssrc);
3069
                                                JANUS_LOG(LOG_VERB, "Got SIP peer video SSRC: %"SCNu32"\n", session->media.video_ssrc_peer);
3070
                                        }
3071
                                        /* Is this SRTP? */
3072
                                        if(session->media.has_srtp_remote) {
3073
                                                int buflen = bytes;
3074
                                                err_status_t res = srtp_unprotect(session->media.video_srtp_in, buffer, &buflen);
3075
                                                if(res != err_status_ok && res != err_status_replay_fail && res != err_status_replay_old) {
3076
                                                        rtp_header *header = (rtp_header *)buffer;
3077
                                                        guint32 timestamp = ntohl(header->timestamp);
3078
                                                        guint16 seq = ntohs(header->seq_number);
3079
                                                        JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTP unprotect error: %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")\n",
3080
                                                                session->account.username, janus_sip_get_srtp_error(res), bytes, buflen, timestamp, seq);
3081
                                                        continue;
3082
                                                }
3083
                                                bytes = buflen;
3084
                                        }
3085
                                        /* Save the frame if we're recording */
3086
                                        if(session->vrc_peer)
3087
                                                janus_recorder_save_frame(session->vrc_peer, buffer, bytes);
3088
                                        /* Relay to browser */
3089
                                        gateway->relay_rtp(session->handle, 1, buffer, bytes);
3090
                                        continue;
3091
                                } else if(session->media.video_rtcp_fd != -1 && fds[i].fd == session->media.video_rtcp_fd) {
3092
                                        /* Got something video (RTCP) */
3093
                                        addrlen = sizeof(remote);
3094
                                        bytes = recvfrom(session->media.video_rtcp_fd, buffer, 1500, 0, (struct sockaddr*)&remote, &addrlen);
3095
                                        //~ JANUS_LOG(LOG_VERB, "************************\nGot %d bytes on the video RTCP channel...\n", bytes);
3096
                                        /* Is this SRTCP? */
3097
                                        if(session->media.has_srtp_remote) {
3098
                                                int buflen = bytes;
3099
                                                err_status_t res = srtp_unprotect_rtcp(session->media.video_srtp_in, buffer, &buflen);
3100
                                                if(res != err_status_ok && res != err_status_replay_fail && res != err_status_replay_old) {
3101
                                                        JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTP unprotect error: %s (len=%d-->%d)\n",
3102
                                                                session->account.username, janus_sip_get_srtp_error(res), bytes, buflen);
3103
                                                        continue;
3104
                                                }
3105
                                                bytes = buflen;
3106
                                        }
3107
                                        /* Relay to browser */
3108
                                        gateway->relay_rtcp(session->handle, 1, buffer, bytes);
3109
                                        continue;
3110
                                }
3111
                        }
3112
                }
3113
        }
3114
        if(session->media.audio_rtp_fd != -1) {
3115
                close(session->media.audio_rtp_fd);
3116
                session->media.audio_rtp_fd = -1;
3117
        }
3118
        if(session->media.audio_rtcp_fd != -1) {
3119
                close(session->media.audio_rtcp_fd);
3120
                session->media.audio_rtcp_fd = -1;
3121
        }
3122
        session->media.local_audio_rtp_port = 0;
3123
        session->media.local_audio_rtcp_port = 0;
3124
        session->media.audio_ssrc = 0;
3125
        if(session->media.video_rtp_fd != -1) {
3126
                close(session->media.video_rtp_fd);
3127
                session->media.video_rtp_fd = -1;
3128
        }
3129
        if(session->media.video_rtcp_fd != -1) {
3130
                close(session->media.video_rtcp_fd);
3131
                session->media.video_rtcp_fd = -1;
3132
        }
3133
        session->media.local_video_rtp_port = 0;
3134
        session->media.local_video_rtcp_port = 0;
3135
        session->media.video_ssrc = 0;
3136
        /* Clean up SRTP stuff, if needed */
3137
        janus_sip_srtp_cleanup(session);
3138
        /* Done */
3139
        JANUS_LOG(LOG_VERB, "Leaving SIP relay thread\n");
3140
        g_thread_unref(g_thread_self());
3141
        return NULL;
3142
}
3143

    
3144

    
3145
/* Sofia Event thread */
3146
gpointer janus_sip_sofia_thread(gpointer user_data) {
3147
        janus_sip_session *session = (janus_sip_session *)user_data;
3148
        if(session == NULL || session->account.username == NULL) {
3149
                g_thread_unref(g_thread_self());
3150
                return NULL;
3151
        }
3152
        JANUS_LOG(LOG_VERB, "Joining sofia loop thread (%s)...\n", session->account.username);
3153
        session->stack = g_malloc0(sizeof(ssip_t));
3154
        session->stack->session = session;
3155
        session->stack->s_nua = NULL;
3156
        session->stack->s_nh_r = NULL;
3157
        session->stack->s_nh_i = NULL;
3158
        session->stack->s_root = su_root_create(session->stack);
3159
        su_home_init(session->stack->s_home);
3160
        JANUS_LOG(LOG_VERB, "Setting up sofia stack (sip:%s@%s)\n", session->account.username, local_ip);
3161
        char sip_url[128];
3162
        char sips_url[128];
3163
        char *ipv6;
3164
        ipv6 = strstr(local_ip, ":");
3165
        g_snprintf(sip_url, sizeof(sip_url), "sip:%s%s%s:*", ipv6 ? "[" : "", local_ip, ipv6 ? "]" : "");
3166
        g_snprintf(sips_url, sizeof(sips_url), "sips:%s%s%s:*", ipv6 ? "[" : "", local_ip, ipv6 ? "]" : "");
3167
        char outbound_options[256] = "use-rport no-validate";
3168
        if(keepalive_interval > 0)
3169
                g_strlcat(outbound_options, " options-keepalive", sizeof(outbound_options));
3170
        if(!behind_nat)
3171
                g_strlcat(outbound_options, " no-natify", sizeof(outbound_options));
3172
        session->stack->s_nua = nua_create(session->stack->s_root,
3173
                                janus_sip_sofia_callback,
3174
                                session,
3175
                                SIPTAG_ALLOW_STR("INVITE, ACK, BYE, CANCEL, OPTIONS"),
3176
                                NUTAG_M_USERNAME(session->account.username),
3177
                                NUTAG_URL(sip_url),
3178
                                TAG_IF(session->account.sips, NUTAG_SIPS_URL(sips_url)),
3179
                                SIPTAG_USER_AGENT_STR(user_agent),
3180
                                NUTAG_KEEPALIVE(keepalive_interval * 1000),        /* Sofia expects it in milliseconds */
3181
                                NUTAG_OUTBOUND(outbound_options),
3182
                                SIPTAG_SUPPORTED(NULL),
3183
                                TAG_NULL());
3184
        su_root_run(session->stack->s_root);
3185
        /* When we get here, we're done */
3186
        nua_destroy(session->stack->s_nua);
3187
        su_root_destroy(session->stack->s_root);
3188
        session->stack->s_root = NULL;
3189
        su_home_deinit(session->stack->s_home);
3190
        su_home_unref(session->stack->s_home);
3191
        su_deinit();
3192
        if (session->stack) {
3193
                g_free(session->stack);
3194
                session->stack = NULL;
3195
        }
3196
        //~ stop = 1;
3197
        JANUS_LOG(LOG_VERB, "Leaving sofia loop thread...\n");
3198
        g_thread_unref(g_thread_self());
3199
        /* Cleaning up and removing the session is done in a lazy way */
3200
        janus_mutex_lock(&sessions_mutex);
3201
        old_sessions = g_list_append(old_sessions, session);
3202
        janus_mutex_unlock(&sessions_mutex);
3203
        return NULL;
3204
}