Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_sip.c @ 372e28b5

History | View | Annotate | Download (126 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
/* Parameter validation */
137
static struct janus_json_parameter request_parameters[] = {
138
        {"request", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
139
};
140
static struct janus_json_parameter register_parameters[] = {
141
        {"type", JSON_STRING, 0},
142
        {"send_register", JANUS_JSON_BOOL, 0},
143
        {"sips", JANUS_JSON_BOOL, 0},
144
        {"username", JSON_STRING, 0},
145
        {"secret", JSON_STRING, 0},
146
        {"ha1_secret", JSON_STRING, 0},
147
        {"authuser", JSON_STRING, 0}
148
};
149
static struct janus_json_parameter proxy_parameters[] = {
150
        {"proxy", JSON_STRING, 0}
151
};
152
static struct janus_json_parameter call_parameters[] = {
153
        {"uri", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
154
        {"headers", JSON_OBJECT, 0},
155
        {"srtp", JSON_STRING, 0}
156
};
157
static struct janus_json_parameter accept_parameters[] = {
158
        {"srtp", JSON_STRING, 0}
159
};
160
static struct janus_json_parameter recording_parameters[] = {
161
        {"action", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
162
        {"audio", JANUS_JSON_BOOL, 0},
163
        {"video", JANUS_JSON_BOOL, 0},
164
        {"peer_audio", JANUS_JSON_BOOL, 0},
165
        {"peer_video", JANUS_JSON_BOOL, 0},
166
        {"filename", JSON_STRING, 0}
167
};
168
static struct janus_json_parameter dtmf_info_parameters[] = {
169
        {"digit", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
170
        {"duration", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE}
171
};
172

    
173
/* Useful stuff */
174
static volatile gint initialized = 0, stopping = 0;
175
static janus_callbacks *gateway = NULL;
176

    
177
static char local_ip[INET6_ADDRSTRLEN];
178
static int keepalive_interval = 120;
179
static gboolean behind_nat = FALSE;
180
static char *user_agent;
181
#define JANUS_DEFAULT_REGISTER_TTL        3600
182
static int register_ttl = JANUS_DEFAULT_REGISTER_TTL;
183

    
184
static GThread *handler_thread;
185
static GThread *watchdog;
186
static void *janus_sip_handler(void *data);
187

    
188
typedef struct janus_sip_message {
189
        janus_plugin_session *handle;
190
        char *transaction;
191
        char *message;
192
        char *sdp_type;
193
        char *sdp;
194
} janus_sip_message;
195
static GAsyncQueue *messages = NULL;
196
static janus_sip_message exit_message;
197

    
198
static void janus_sip_message_free(janus_sip_message *msg) {
199
        if(!msg || msg == &exit_message)
200
                return;
201

    
202
        msg->handle = NULL;
203

    
204
        g_free(msg->transaction);
205
        msg->transaction = NULL;
206
        g_free(msg->message);
207
        msg->message = NULL;
208
        g_free(msg->sdp_type);
209
        msg->sdp_type = NULL;
210
        g_free(msg->sdp);
211
        msg->sdp = NULL;
212

    
213
        g_free(msg);
214
}
215

    
216

    
217
typedef enum {
218
        janus_sip_registration_status_disabled = -2,
219
        janus_sip_registration_status_failed = -1,
220
        janus_sip_registration_status_unregistered = 0,
221
        janus_sip_registration_status_registering,
222
        janus_sip_registration_status_registered,
223
        janus_sip_registration_status_unregistering,
224
} janus_sip_registration_status;
225

    
226
static const char *janus_sip_registration_status_string(janus_sip_registration_status status) {
227
        switch(status) {
228
                case janus_sip_registration_status_disabled:
229
                        return "disabled";
230
                case janus_sip_registration_status_failed:
231
                        return "failed";
232
                case janus_sip_registration_status_unregistered:
233
                        return "unregistered";
234
                case janus_sip_registration_status_registering:
235
                        return "registering";
236
                case janus_sip_registration_status_registered:
237
                        return "registered";
238
                case janus_sip_registration_status_unregistering:
239
                        return "unregistering";
240
                default:
241
                        return "unknown";
242
        }
243
}
244

    
245

    
246
typedef enum {
247
        janus_sip_call_status_idle = 0,
248
        janus_sip_call_status_inviting,
249
        janus_sip_call_status_invited,
250
        janus_sip_call_status_incall,
251
        janus_sip_call_status_closing,
252
} janus_sip_call_status;
253

    
254
static const char *janus_sip_call_status_string(janus_sip_call_status status) {
255
        switch(status) {
256
                case janus_sip_call_status_idle:
257
                        return "idle";
258
                case janus_sip_call_status_inviting:
259
                        return "inviting";
260
                case janus_sip_call_status_invited:
261
                        return "invited";
262
                case janus_sip_call_status_incall:
263
                        return "incall";
264
                case janus_sip_call_status_closing:
265
                        return "closing";
266
                default:
267
                        return "unknown";
268
        }
269
}
270

    
271

    
272
/* Sofia stuff */
273
typedef struct ssip_s ssip_t;
274
typedef struct ssip_oper_s ssip_oper_t;
275

    
276
typedef enum {
277
        janus_sip_secret_type_plaintext = 1,
278
        janus_sip_secret_type_hashed = 2,
279
        janus_sip_secret_type_unknown
280
} janus_sip_secret_type;
281

    
282
typedef struct janus_sip_account {
283
        char *identity;
284
        char *user_agent;                /* Used to override the general UA string */
285
        gboolean sips;
286
        char *username;
287
        char *display_name;                /* Used for outgoing calls in the From header */
288
        char *authuser;                        /**< username to use for authentication */
289
        char *secret;
290
        janus_sip_secret_type secret_type;
291
        int sip_port;
292
        char *proxy;
293
        janus_sip_registration_status registration_status;
294
} janus_sip_account;
295

    
296
typedef struct janus_sip_media {
297
        char *remote_ip;
298
        int ready:1;
299
        gboolean require_srtp, has_srtp_local, has_srtp_remote;
300
        int has_audio:1;
301
        int audio_rtp_fd, audio_rtcp_fd;
302
        int local_audio_rtp_port, remote_audio_rtp_port;
303
        int local_audio_rtcp_port, remote_audio_rtcp_port;
304
        guint32 audio_ssrc, audio_ssrc_peer;
305
        int audio_pt;
306
        const char *audio_pt_name;
307
        srtp_t audio_srtp_in, audio_srtp_out;
308
        srtp_policy_t audio_remote_policy, audio_local_policy;
309
        int audio_srtp_suite_in, audio_srtp_suite_out;
310
        int has_video:1;
311
        int video_rtp_fd, video_rtcp_fd;
312
        int local_video_rtp_port, remote_video_rtp_port;
313
        int local_video_rtcp_port, remote_video_rtcp_port;
314
        guint32 video_ssrc, video_ssrc_peer;
315
        int video_pt;
316
        const char *video_pt_name;
317
        srtp_t video_srtp_in, video_srtp_out;
318
        srtp_policy_t video_remote_policy, video_local_policy;
319
        int video_srtp_suite_in, video_srtp_suite_out;
320
} janus_sip_media;
321

    
322
typedef struct janus_sip_session {
323
        janus_plugin_session *handle;
324
        ssip_t *stack;
325
        janus_sip_account account;
326
        janus_sip_call_status status;
327
        janus_sip_media media;
328
        char *transaction;
329
        char *callee;
330
        janus_recorder *arc;                /* The Janus recorder instance for this user's audio, if enabled */
331
        janus_recorder *arc_peer;        /* The Janus recorder instance for the peer's audio, if enabled */
332
        janus_recorder *vrc;                /* The Janus recorder instance for this user's video, if enabled */
333
        janus_recorder *vrc_peer;        /* The Janus recorder instance for the peer's video, if enabled */
334
        janus_mutex rec_mutex;                /* Mutex to protect the recorders from race conditions */
335
        volatile gint hangingup;
336
        gint64 destroyed;        /* Time at which this session was marked as destroyed */
337
        janus_mutex mutex;
338
} janus_sip_session;
339
static GHashTable *sessions;
340
static GList *old_sessions;
341
static janus_mutex sessions_mutex;
342

    
343

    
344
#undef SU_ROOT_MAGIC_T
345
#define SU_ROOT_MAGIC_T        ssip_t
346
#undef NUA_MAGIC_T
347
#define NUA_MAGIC_T                ssip_t
348
#undef NUA_HMAGIC_T
349
#define NUA_HMAGIC_T        ssip_oper_t
350

    
351
struct ssip_s {
352
        su_home_t s_home[1];
353
        su_root_t *s_root;
354
        nua_t *s_nua;
355
        nua_handle_t *s_nh_r, *s_nh_i;
356
        janus_sip_session *session;
357
};
358

    
359

    
360
/* SRTP stuff (in case we need SDES) */
361
#define SRTP_MASTER_KEY_LENGTH        16
362
#define SRTP_MASTER_SALT_LENGTH        14
363
#define SRTP_MASTER_LENGTH (SRTP_MASTER_KEY_LENGTH + SRTP_MASTER_SALT_LENGTH)
364
static const char *janus_sip_srtp_error[] =
365
{
366
        "err_status_ok",
367
        "err_status_fail",
368
        "err_status_bad_param",
369
        "err_status_alloc_fail",
370
        "err_status_dealloc_fail",
371
        "err_status_init_fail",
372
        "err_status_terminus",
373
        "err_status_auth_fail",
374
        "err_status_cipher_fail",
375
        "err_status_replay_fail",
376
        "err_status_replay_old",
377
        "err_status_algo_fail",
378
        "err_status_no_such_op",
379
        "err_status_no_ctx",
380
        "err_status_cant_check",
381
        "err_status_key_expired",
382
        "err_status_socket_err",
383
        "err_status_signal_err",
384
        "err_status_nonce_bad",
385
        "err_status_read_fail",
386
        "err_status_write_fail",
387
        "err_status_parse_err",
388
        "err_status_encode_err",
389
        "err_status_semaphore_err",
390
        "err_status_pfkey_err",
391
};
392
static const gchar *janus_sip_get_srtp_error(int error) {
393
        if(error < 0 || error > 24)
394
                return NULL;
395
        return janus_sip_srtp_error[error];
396
}
397
static int janus_sip_srtp_set_local(janus_sip_session *session, gboolean video, char **crypto) {
398
        if(session == NULL)
399
                return -1;
400
        /* Generate key/salt */
401
        uint8_t *key = g_malloc0(SRTP_MASTER_LENGTH);
402
        crypto_get_random(key, SRTP_MASTER_LENGTH);
403
        /* Set SRTP policies */
404
        srtp_policy_t *policy = video ? &session->media.video_local_policy : &session->media.audio_local_policy;
405
        crypto_policy_set_rtp_default(&(policy->rtp));
406
        crypto_policy_set_rtcp_default(&(policy->rtcp));
407
        policy->ssrc.type = ssrc_any_inbound;
408
        policy->key = key;
409
        policy->next = NULL;
410
        /* Create SRTP context */
411
        err_status_t res = srtp_create(video ? &session->media.video_srtp_out : &session->media.audio_srtp_out, policy);
412
        if(res != err_status_ok) {
413
                /* Something went wrong... */
414
                JANUS_LOG(LOG_ERR, "Oops, error creating outbound SRTP session: %d (%s)\n", res, janus_sip_get_srtp_error(res));
415
                g_free(key);
416
                policy->key = NULL;
417
                return -2;
418
        }
419
        /* Base64 encode the salt */
420
        *crypto = g_base64_encode(key, SRTP_MASTER_LENGTH);
421
        if((video && session->media.video_srtp_out) || (!video && session->media.audio_srtp_out)) {
422
                JANUS_LOG(LOG_VERB, "%s outbound SRTP session created\n", video ? "Video" : "Audio");
423
        }
424
        return 0;
425
}
426
static int janus_sip_srtp_set_remote(janus_sip_session *session, gboolean video, const char *crypto, int suite) {
427
        if(session == NULL || crypto == NULL)
428
                return -1;
429
        /* Base64 decode the crypto string and set it as the remote SRTP context */
430
        gsize len = 0;
431
        guchar *decoded = g_base64_decode(crypto, &len);
432
        if(len < SRTP_MASTER_LENGTH) {
433
                /* FIXME Can this happen? */
434
                g_free(decoded);
435
                return -2;
436
        }
437
        /* Set SRTP policies */
438
        srtp_policy_t *policy = video ? &session->media.video_remote_policy : &session->media.audio_remote_policy;
439
        crypto_policy_set_rtp_default(&(policy->rtp));
440
        crypto_policy_set_rtcp_default(&(policy->rtcp));
441
        if(suite == 32) {
442
                crypto_policy_set_aes_cm_128_hmac_sha1_32(&(policy->rtp));
443
                crypto_policy_set_aes_cm_128_hmac_sha1_32(&(policy->rtcp));
444
        } else if(suite == 80) {
445
                crypto_policy_set_aes_cm_128_hmac_sha1_80(&(policy->rtp));
446
                crypto_policy_set_aes_cm_128_hmac_sha1_80(&(policy->rtcp));
447
        }
448
        policy->ssrc.type = ssrc_any_inbound;
449
        policy->key = decoded;
450
        policy->next = NULL;
451
        /* Create SRTP context */
452
        err_status_t res = srtp_create(video ? &session->media.video_srtp_in : &session->media.audio_srtp_in, policy);
453
        if(res != err_status_ok) {
454
                /* Something went wrong... */
455
                JANUS_LOG(LOG_ERR, "Oops, error creating inbound SRTP session: %d (%s)\n", res, janus_sip_get_srtp_error(res));
456
                g_free(decoded);
457
                policy->key = NULL;
458
                return -2;
459
        }
460
        if((video && session->media.video_srtp_in) || (!video && session->media.audio_srtp_in)) {
461
                JANUS_LOG(LOG_VERB, "%s inbound SRTP session created\n", video ? "Video" : "Audio");
462
        }
463
        return 0;
464
}
465
static void janus_sip_srtp_cleanup(janus_sip_session *session) {
466
        if(session == NULL)
467
                return;
468
        session->media.require_srtp = FALSE;
469
        session->media.has_srtp_local = FALSE;
470
        session->media.has_srtp_remote = FALSE;
471
        /* Audio */
472
        if(session->media.audio_srtp_out)
473
                srtp_dealloc(session->media.audio_srtp_out);
474
        session->media.audio_srtp_out = NULL;
475
        g_free(session->media.audio_local_policy.key);
476
        session->media.audio_local_policy.key = NULL;
477
        session->media.audio_srtp_suite_out = 0;
478
        if(session->media.audio_srtp_in)
479
                srtp_dealloc(session->media.audio_srtp_in);
480
        session->media.audio_srtp_in = NULL;
481
        g_free(session->media.audio_remote_policy.key);
482
        session->media.audio_remote_policy.key = NULL;
483
        session->media.audio_srtp_suite_in = 0;
484
        /* Video */
485
        if(session->media.video_srtp_out)
486
                srtp_dealloc(session->media.video_srtp_out);
487
        session->media.video_srtp_out = NULL;
488
        g_free(session->media.video_local_policy.key);
489
        session->media.video_local_policy.key = NULL;
490
        session->media.video_srtp_suite_out = 0;
491
        if(session->media.video_srtp_in)
492
                srtp_dealloc(session->media.video_srtp_in);
493
        session->media.video_srtp_in = NULL;
494
        g_free(session->media.video_remote_policy.key);
495
        session->media.video_remote_policy.key = NULL;
496
        session->media.video_srtp_suite_in = 0;
497
}
498

    
499

    
500
/* Sofia Event thread */
501
gpointer janus_sip_sofia_thread(gpointer user_data);
502
/* Sofia callbacks */
503
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[]);
504
/* SDP parsing and manipulation */
505
void janus_sip_sdp_process(janus_sip_session *session, sdp_session_t *sdp, gboolean answer);
506
char *janus_sip_sdp_manipulate(janus_sip_session *session, sdp_session_t *sdp, gboolean answer);
507
/* Media */
508
static int janus_sip_allocate_local_ports(janus_sip_session *session);
509
static void *janus_sip_relay_thread(void *data);
510

    
511

    
512
/* URI parsing utilies */
513

    
514
#define JANUS_SIP_URI_MAXLEN        1024
515
typedef struct {
516
        char data[JANUS_SIP_URI_MAXLEN];
517
        url_t url[1];
518
} janus_sip_uri_t;
519

    
520
/* Parses a SIP URI (SIPS is not supported), returns 0 on success, -1 otherwise */
521
static int janus_sip_parse_uri(janus_sip_uri_t *sip_uri, const char *data) {
522
        g_strlcpy(sip_uri->data, data, JANUS_SIP_URI_MAXLEN);
523
        if (url_d(sip_uri->url, sip_uri->data) < 0 || sip_uri->url->url_type != url_sip)
524
                return -1;
525
        return 0;
526
}
527

    
528
/* Similar to the above function, but it also accepts SIPS URIs */
529
static int janus_sip_parse_proxy_uri(janus_sip_uri_t *sip_uri, const char *data) {
530
        g_strlcpy(sip_uri->data, data, JANUS_SIP_URI_MAXLEN);
531
        if (url_d(sip_uri->url, sip_uri->data) < 0 || (sip_uri->url->url_type != url_sip && sip_uri->url->url_type != url_sips))
532
                return -1;
533
        return 0;
534
}
535

    
536
/* Error codes */
537
#define JANUS_SIP_ERROR_UNKNOWN_ERROR                499
538
#define JANUS_SIP_ERROR_NO_MESSAGE                        440
539
#define JANUS_SIP_ERROR_INVALID_JSON                441
540
#define JANUS_SIP_ERROR_INVALID_REQUEST                442
541
#define JANUS_SIP_ERROR_MISSING_ELEMENT                443
542
#define JANUS_SIP_ERROR_INVALID_ELEMENT                444
543
#define JANUS_SIP_ERROR_ALREADY_REGISTERED        445
544
#define JANUS_SIP_ERROR_INVALID_ADDRESS                446
545
#define JANUS_SIP_ERROR_WRONG_STATE                        447
546
#define JANUS_SIP_ERROR_MISSING_SDP                        448
547
#define JANUS_SIP_ERROR_LIBSOFIA_ERROR                449
548
#define JANUS_SIP_ERROR_IO_ERROR                        450
549
#define JANUS_SIP_ERROR_RECORDING_ERROR                451
550
#define JANUS_SIP_ERROR_TOO_STRICT                        452
551

    
552

    
553
/* SIP watchdog/garbage collector (sort of) */
554
void *janus_sip_watchdog(void *data);
555
void *janus_sip_watchdog(void *data) {
556
        JANUS_LOG(LOG_INFO, "SIP watchdog started\n");
557
        gint64 now = 0;
558
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
559
                janus_mutex_lock(&sessions_mutex);
560
                /* Iterate on all the sessions */
561
                now = janus_get_monotonic_time();
562
                if(old_sessions != NULL) {
563
                        GList *sl = old_sessions;
564
                        JANUS_LOG(LOG_HUGE, "Checking %d old SIP sessions...\n", g_list_length(old_sessions));
565
                        while(sl) {
566
                                janus_sip_session *session = (janus_sip_session *)sl->data;
567
                                if(!session) {
568
                                        sl = sl->next;
569
                                        continue;
570
                                }
571
                                if (now-session->destroyed >= 5*G_USEC_PER_SEC) {
572
                                        /* We're lazy and actually get rid of the stuff only after a few seconds */
573
                                        JANUS_LOG(LOG_VERB, "Freeing old SIP session\n");
574
                                        GList *rm = sl->next;
575
                                        old_sessions = g_list_delete_link(old_sessions, sl);
576
                                        sl = rm;
577
                                        if (session->account.identity) {
578
                                            g_free(session->account.identity);
579
                                            session->account.identity = NULL;
580
                                        }
581
                                        session->account.sips = TRUE;
582
                                        if (session->account.proxy) {
583
                                            g_free(session->account.proxy);
584
                                            session->account.proxy = NULL;
585
                                        }
586
                                        if (session->account.secret) {
587
                                            g_free(session->account.secret);
588
                                            session->account.secret = NULL;
589
                                        }
590
                                        if (session->account.username) {
591
                                            g_free(session->account.username);
592
                                            session->account.username = NULL;
593
                                        }
594
                                        if (session->account.display_name) {
595
                                            g_free(session->account.display_name);
596
                                            session->account.display_name = NULL;
597
                                        }
598
                                        if (session->account.user_agent) {
599
                                            g_free(session->account.user_agent);
600
                                            session->account.user_agent = NULL;
601
                                        }
602
                                        if (session->account.authuser) {
603
                                            g_free(session->account.authuser);
604
                                            session->account.authuser = NULL;
605
                                        }
606
                                        if (session->callee) {
607
                                            g_free(session->callee);
608
                                            session->callee = NULL;
609
                                        }
610
                                        if (session->transaction) {
611
                                            g_free(session->transaction);
612
                                            session->transaction = NULL;
613
                                        }
614
                                        if (session->media.remote_ip) {
615
                                            g_free(session->media.remote_ip);
616
                                            session->media.remote_ip = NULL;
617
                                        }
618
                                        janus_sip_srtp_cleanup(session);
619
                                        session->handle = NULL;
620
                                        g_free(session);
621
                                        session = NULL;
622
                                        continue;
623
                                }
624
                                sl = sl->next;
625
                        }
626
                }
627
                janus_mutex_unlock(&sessions_mutex);
628
                g_usleep(500000);
629
        }
630
        JANUS_LOG(LOG_INFO, "SIP watchdog stopped\n");
631
        return NULL;
632
}
633

    
634

    
635
static void janus_sip_detect_local_ip(char *buf, size_t buflen) {
636
        JANUS_LOG(LOG_VERB, "Autodetecting local IP...\n");
637

    
638
        struct sockaddr_in addr;
639
        socklen_t len;
640
        int fd = socket(AF_INET, SOCK_DGRAM, 0);
641
        if (fd == -1)
642
                goto error;
643
        addr.sin_family = AF_INET;
644
        addr.sin_port = htons(1);
645
        inet_pton(AF_INET, "1.2.3.4", &addr.sin_addr.s_addr);
646
        if (connect(fd, (const struct sockaddr*) &addr, sizeof(addr)) < 0)
647
                goto error;
648
        len = sizeof(addr);
649
        if (getsockname(fd, (struct sockaddr*) &addr, &len) < 0)
650
                goto error;
651
        if (getnameinfo((const struct sockaddr*) &addr, sizeof(addr),
652
                        buf, buflen,
653
                        NULL, 0, NI_NUMERICHOST) != 0)
654
                goto error;
655
        close(fd);
656
        return;
657

    
658
error:
659
        if (fd != -1)
660
                close(fd);
661
        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");
662
        g_strlcpy(buf, "127.0.0.1", buflen);
663
}
664

    
665

    
666
/* Plugin implementation */
667
int janus_sip_init(janus_callbacks *callback, const char *config_path) {
668
        if(g_atomic_int_get(&stopping)) {
669
                /* Still stopping from before */
670
                return -1;
671
        }
672
        if(callback == NULL || config_path == NULL) {
673
                /* Invalid arguments */
674
                return -1;
675
        }
676

    
677
        /* Read configuration */
678
        char filename[255];
679
        g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_SIP_PACKAGE);
680
        JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
681
        janus_config *config = janus_config_parse(filename);
682
        if(config != NULL)
683
                janus_config_print(config);
684

    
685
        gboolean local_ip_set = FALSE;
686
        janus_config_item *item = janus_config_get_item_drilldown(config, "general", "local_ip");
687
        if(item && item->value) {
688
                int family;
689
                if (!janus_is_ip_valid(item->value, &family)) {
690
                        JANUS_LOG(LOG_WARN, "Invalid local IP specified: %s, guessing the default...\n", item->value);
691
                } else {
692
                        /* Verify that we can actually bind to that address */
693
                        int fd = socket(family, SOCK_DGRAM, 0);
694
                        if (fd == -1) {
695
                                JANUS_LOG(LOG_WARN, "Error creating test socket, falling back to detecting IP address...\n");
696
                        } else {
697
                                int r;
698
                                struct sockaddr_storage ss;
699
                                socklen_t addrlen;
700
                                memset(&ss, 0, sizeof(ss));
701
                                if (family == AF_INET) {
702
                                        struct sockaddr_in *addr4 = (struct sockaddr_in*)&ss;
703
                                        addr4->sin_family = AF_INET;
704
                                        addr4->sin_port = 0;
705
                                        inet_pton(AF_INET, item->value, &(addr4->sin_addr.s_addr));
706
                                        addrlen = sizeof(struct sockaddr_in);
707
                                } else {
708
                                        struct sockaddr_in6 *addr6 = (struct sockaddr_in6*)&ss;
709
                                        addr6->sin6_family = AF_INET6;
710
                                        addr6->sin6_port = 0;
711
                                        inet_pton(AF_INET6, item->value, &(addr6->sin6_addr.s6_addr));
712
                                        addrlen = sizeof(struct sockaddr_in6);
713
                                }
714
                                r = bind(fd, (const struct sockaddr*)&ss, addrlen);
715
                                close(fd);
716
                                if (r < 0) {
717
                                        JANUS_LOG(LOG_WARN, "Error setting local IP address to %s, falling back to detecting IP address...\n", item->value);
718
                                } else {
719
                                        g_strlcpy(local_ip, item->value, sizeof(local_ip));
720
                                        local_ip_set = TRUE;
721
                                }
722
                        }
723
                }
724
        }
725
        if (!local_ip_set)
726
                janus_sip_detect_local_ip(local_ip, sizeof(local_ip));
727
        JANUS_LOG(LOG_VERB, "Local IP set to %s\n", local_ip);
728

    
729
        item = janus_config_get_item_drilldown(config, "general", "keepalive_interval");
730
        if(item && item->value)
731
                keepalive_interval = atoi(item->value);
732
        JANUS_LOG(LOG_VERB, "SIP keep-alive interval set to %d seconds\n", keepalive_interval);
733

    
734
        item = janus_config_get_item_drilldown(config, "general", "register_ttl");
735
        if(item && item->value)
736
                register_ttl = atoi(item->value);
737
        JANUS_LOG(LOG_VERB, "SIP registration TTL set to %d seconds\n", register_ttl);
738

    
739
        item = janus_config_get_item_drilldown(config, "general", "behind_nat");
740
        if(item && item->value)
741
                behind_nat = janus_is_true(item->value);
742

    
743
        item = janus_config_get_item_drilldown(config, "general", "user_agent");
744
        if(item && item->value)
745
                user_agent = g_strdup(item->value);
746
        else
747
                user_agent = g_strdup("Janus WebRTC Gateway SIP Plugin "JANUS_SIP_VERSION_STRING);
748
        JANUS_LOG(LOG_VERB, "SIP User-Agent set to %s\n", user_agent);
749

    
750
        /* This plugin actually has nothing to configure... */
751
        janus_config_destroy(config);
752
        config = NULL;
753

    
754
        /* Setup sofia */
755
        su_init();
756

    
757
        sessions = g_hash_table_new(NULL, NULL);
758
        janus_mutex_init(&sessions_mutex);
759
        messages = g_async_queue_new_full((GDestroyNotify) janus_sip_message_free);
760
        /* This is the callback we'll need to invoke to contact the gateway */
761
        gateway = callback;
762

    
763
        g_atomic_int_set(&initialized, 1);
764

    
765
        GError *error = NULL;
766
        /* Start the sessions watchdog */
767
        watchdog = g_thread_try_new("etest watchdog", &janus_sip_watchdog, NULL, &error);
768
        if(error != NULL) {
769
                g_atomic_int_set(&initialized, 0);
770
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP watchdog thread...\n", error->code, error->message ? error->message : "??");
771
                return -1;
772
        }
773
        /* Launch the thread that will handle incoming messages */
774
        handler_thread = g_thread_try_new("janus sip handler", janus_sip_handler, NULL, &error);
775
        if(error != NULL) {
776
                g_atomic_int_set(&initialized, 0);
777
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP handler thread...\n", error->code, error->message ? error->message : "??");
778
                return -1;
779
        }
780
        JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_SIP_NAME);
781
        return 0;
782
}
783

    
784
void janus_sip_destroy(void) {
785
        if(!g_atomic_int_get(&initialized))
786
                return;
787
        g_atomic_int_set(&stopping, 1);
788

    
789
        g_async_queue_push(messages, &exit_message);
790
        if(handler_thread != NULL) {
791
                g_thread_join(handler_thread);
792
                handler_thread = NULL;
793
        }
794
        if(watchdog != NULL) {
795
                g_thread_join(watchdog);
796
                watchdog = NULL;
797
        }
798
        /* FIXME We should destroy the sessions cleanly */
799
        janus_mutex_lock(&sessions_mutex);
800
        g_hash_table_destroy(sessions);
801
        janus_mutex_unlock(&sessions_mutex);
802
        g_async_queue_unref(messages);
803
        messages = NULL;
804
        sessions = NULL;
805
        g_atomic_int_set(&initialized, 0);
806
        g_atomic_int_set(&stopping, 0);
807
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_SIP_NAME);
808
}
809

    
810
int janus_sip_get_api_compatibility(void) {
811
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
812
        return JANUS_PLUGIN_API_VERSION;
813
}
814

    
815
int janus_sip_get_version(void) {
816
        return JANUS_SIP_VERSION;
817
}
818

    
819
const char *janus_sip_get_version_string(void) {
820
        return JANUS_SIP_VERSION_STRING;
821
}
822

    
823
const char *janus_sip_get_description(void) {
824
        return JANUS_SIP_DESCRIPTION;
825
}
826

    
827
const char *janus_sip_get_name(void) {
828
        return JANUS_SIP_NAME;
829
}
830

    
831
const char *janus_sip_get_author(void) {
832
        return JANUS_SIP_AUTHOR;
833
}
834

    
835
const char *janus_sip_get_package(void) {
836
        return JANUS_SIP_PACKAGE;
837
}
838

    
839
void janus_sip_create_session(janus_plugin_session *handle, int *error) {
840
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
841
                *error = -1;
842
                return;
843
        }
844
        janus_sip_session *session = g_malloc0(sizeof(janus_sip_session));
845
        session->handle = handle;
846
        session->account.identity = NULL;
847
        session->account.sips = TRUE;
848
        session->account.username = NULL;
849
        session->account.display_name = NULL;
850
        session->account.user_agent = NULL;
851
        session->account.authuser = NULL;
852
        session->account.secret = NULL;
853
        session->account.secret_type = janus_sip_secret_type_unknown;
854
        session->account.sip_port = 0;
855
        session->account.proxy = NULL;
856
        session->account.registration_status = janus_sip_registration_status_unregistered;
857
        session->status = janus_sip_call_status_idle;
858
        session->stack = NULL;
859
        session->transaction = NULL;
860
        session->callee = NULL;
861
        session->media.remote_ip = NULL;
862
        session->media.ready = 0;
863
        session->media.require_srtp = FALSE;
864
        session->media.has_srtp_local = FALSE;
865
        session->media.has_srtp_remote = FALSE;
866
        session->media.has_audio = 0;
867
        session->media.audio_rtp_fd = -1;
868
        session->media.audio_rtcp_fd= -1;
869
        session->media.local_audio_rtp_port = 0;
870
        session->media.remote_audio_rtp_port = 0;
871
        session->media.local_audio_rtcp_port = 0;
872
        session->media.remote_audio_rtcp_port = 0;
873
        session->media.audio_ssrc = 0;
874
        session->media.audio_ssrc_peer = 0;
875
        session->media.audio_pt = -1;
876
        session->media.audio_pt_name = NULL;
877
        session->media.audio_srtp_suite_in = 0;
878
        session->media.audio_srtp_suite_out = 0;
879
        session->media.has_video = 0;
880
        session->media.video_rtp_fd = -1;
881
        session->media.video_rtcp_fd= -1;
882
        session->media.local_video_rtp_port = 0;
883
        session->media.remote_video_rtp_port = 0;
884
        session->media.local_video_rtcp_port = 0;
885
        session->media.remote_video_rtcp_port = 0;
886
        session->media.video_ssrc = 0;
887
        session->media.video_ssrc_peer = 0;
888
        session->media.video_pt = -1;
889
        session->media.video_pt_name = NULL;
890
        session->media.video_srtp_suite_in = 0;
891
        session->media.video_srtp_suite_out = 0;
892
        janus_mutex_init(&session->rec_mutex);
893
        session->destroyed = 0;
894
        g_atomic_int_set(&session->hangingup, 0);
895
        janus_mutex_init(&session->mutex);
896
        handle->plugin_handle = session;
897

    
898
        janus_mutex_lock(&sessions_mutex);
899
        g_hash_table_insert(sessions, handle, session);
900
        janus_mutex_unlock(&sessions_mutex);
901

    
902
        return;
903
}
904

    
905
void janus_sip_destroy_session(janus_plugin_session *handle, int *error) {
906
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
907
                *error = -1;
908
                return;
909
        }
910
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
911
        if(!session) {
912
                JANUS_LOG(LOG_ERR, "No SIP session associated with this handle...\n");
913
                *error = -2;
914
                return;
915
        }
916
        janus_mutex_lock(&sessions_mutex);
917
        if(!session->destroyed) {
918
                g_hash_table_remove(sessions, handle);
919
                janus_sip_hangup_media(handle);
920
                session->destroyed = janus_get_monotonic_time();
921
                JANUS_LOG(LOG_VERB, "Destroying SIP session (%s)...\n", session->account.username ? session->account.username : "unregistered user");
922
                if(session->stack != NULL) {
923
                        /* Shutdown the NUA: this will remove the session later on */
924
                        nua_shutdown(session->stack->s_nua);
925
                } else {
926
                        /* No stack, maybe never registered: cleaning up and removing the session is done in a lazy way */
927
                        old_sessions = g_list_append(old_sessions, session);
928
                }
929
        }
930
        janus_mutex_unlock(&sessions_mutex);
931
        return;
932
}
933

    
934
char *janus_sip_query_session(janus_plugin_session *handle) {
935
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
936
                return NULL;
937
        }
938
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
939
        if(!session) {
940
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
941
                return NULL;
942
        }
943
        /* Provide some generic info, e.g., if we're in a call and with whom */
944
        json_t *info = json_object();
945
        json_object_set_new(info, "username", session->account.username ? json_string(session->account.username) : NULL);
946
        json_object_set_new(info, "display_name", session->account.display_name ? json_string(session->account.display_name) : NULL);
947
        json_object_set_new(info, "user_agent", session->account.user_agent ? json_string(session->account.user_agent) : NULL);
948
        json_object_set_new(info, "identity", session->account.identity ? json_string(session->account.identity) : NULL);
949
        json_object_set_new(info, "registration_status", json_string(janus_sip_registration_status_string(session->account.registration_status)));
950
        json_object_set_new(info, "call_status", json_string(janus_sip_call_status_string(session->status)));
951
        if(session->callee) {
952
                json_object_set_new(info, "callee", json_string(session->callee ? session->callee : "??"));
953
                json_object_set_new(info, "srtp-required", json_string(session->media.require_srtp ? "yes" : "no"));
954
                json_object_set_new(info, "sdes-local", json_string(session->media.has_srtp_local ? "yes" : "no"));
955
                json_object_set_new(info, "sdes-remote", json_string(session->media.has_srtp_remote ? "yes" : "no"));
956
        }
957
        if(session->arc || session->vrc || session->arc_peer || session->vrc_peer) {
958
                json_t *recording = json_object();
959
                if(session->arc && session->arc->filename)
960
                        json_object_set_new(recording, "audio", json_string(session->arc->filename));
961
                if(session->vrc && session->vrc->filename)
962
                        json_object_set_new(recording, "video", json_string(session->vrc->filename));
963
                if(session->arc_peer && session->arc_peer->filename)
964
                        json_object_set_new(recording, "audio-peer", json_string(session->arc_peer->filename));
965
                if(session->vrc_peer && session->vrc_peer->filename)
966
                        json_object_set_new(recording, "video-peer", json_string(session->vrc_peer->filename));
967
                json_object_set_new(info, "recording", recording);
968
        }
969
        json_object_set_new(info, "destroyed", json_integer(session->destroyed));
970
        char *info_text = json_dumps(info, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
971
        json_decref(info);
972
        return info_text;
973
}
974

    
975
struct janus_plugin_result *janus_sip_handle_message(janus_plugin_session *handle, char *transaction, char *message, char *sdp_type, char *sdp) {
976
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
977
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized");
978
        JANUS_LOG(LOG_VERB, "%s\n", message);
979
        janus_sip_message *msg = g_malloc0(sizeof(janus_sip_message));
980
        msg->handle = handle;
981
        msg->transaction = transaction;
982
        msg->message = message;
983
        msg->sdp_type = sdp_type;
984
        msg->sdp = sdp;
985
        g_async_queue_push(messages, msg);
986

    
987
        /* All the requests to this plugin are handled asynchronously */
988
        return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL);
989
}
990

    
991
void janus_sip_setup_media(janus_plugin_session *handle) {
992
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
993
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
994
                return;
995
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
996
        if(!session) {
997
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
998
                return;
999
        }
1000
        if(session->destroyed)
1001
                return;
1002
        g_atomic_int_set(&session->hangingup, 0);
1003
        /* TODO Only relay RTP/RTCP when we get this event */
1004
}
1005

    
1006
void janus_sip_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len) {
1007
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1008
                return;
1009
        if(gateway) {
1010
                /* Honour the audio/video active flags */
1011
                janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1012
                if(!session || session->destroyed) {
1013
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1014
                        return;
1015
                }
1016
                if(session->status != janus_sip_call_status_incall)
1017
                        return;
1018
                /* Forward to our SIP peer */
1019
                if(video) {
1020
                        if(session->media.video_ssrc == 0) {
1021
                                rtp_header *header = (rtp_header *)buf;
1022
                                session->media.video_ssrc = ntohl(header->ssrc);
1023
                                JANUS_LOG(LOG_VERB, "Got SIP video SSRC: %"SCNu32"\n", session->media.video_ssrc);
1024
                        }
1025
                        if(session->media.has_video && session->media.video_rtp_fd) {
1026
                                /* Save the frame if we're recording */
1027
                                janus_recorder_save_frame(session->vrc, buf, len);
1028
                                /* Is SRTP involved? */
1029
                                if(session->media.has_srtp_local) {
1030
                                        char sbuf[2048];
1031
                                        memcpy(&sbuf, buf, len);
1032
                                        int protected = len;
1033
                                        int res = srtp_protect(session->media.video_srtp_out, &sbuf, &protected);
1034
                                        if(res != err_status_ok) {
1035
                                                rtp_header *header = (rtp_header *)&sbuf;
1036
                                                guint32 timestamp = ntohl(header->timestamp);
1037
                                                guint16 seq = ntohs(header->seq_number);
1038
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTP protect error... %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")...\n",
1039
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected, timestamp, seq);
1040
                                        } else {
1041
                                                /* Forward the frame to the peer */
1042
                                                send(session->media.video_rtp_fd, sbuf, protected, 0);
1043
                                        }
1044
                                } else {
1045
                                        /* Forward the frame to the peer */
1046
                                        send(session->media.video_rtp_fd, buf, len, 0);
1047
                                }
1048
                        }
1049
                } else {
1050
                        if(session->media.audio_ssrc == 0) {
1051
                                rtp_header *header = (rtp_header *)buf;
1052
                                session->media.audio_ssrc = ntohl(header->ssrc);
1053
                                JANUS_LOG(LOG_VERB, "Got SIP audio SSRC: %"SCNu32"\n", session->media.audio_ssrc);
1054
                        }
1055
                        if(session->media.has_audio && session->media.audio_rtp_fd) {
1056
                                /* Save the frame if we're recording */
1057
                                janus_recorder_save_frame(session->arc, buf, len);
1058
                                /* Is SRTP involved? */
1059
                                if(session->media.has_srtp_local) {
1060
                                        char sbuf[2048];
1061
                                        memcpy(&sbuf, buf, len);
1062
                                        int protected = len;
1063
                                        int res = srtp_protect(session->media.audio_srtp_out, &sbuf, &protected);
1064
                                        if(res != err_status_ok) {
1065
                                                rtp_header *header = (rtp_header *)&sbuf;
1066
                                                guint32 timestamp = ntohl(header->timestamp);
1067
                                                guint16 seq = ntohs(header->seq_number);
1068
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTP protect error... %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")...\n",
1069
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected, timestamp, seq);
1070
                                        } else {
1071
                                                /* Forward the frame to the peer */
1072
                                                send(session->media.audio_rtp_fd, sbuf, protected, 0);
1073
                                        }
1074
                                } else {
1075
                                        /* Forward the frame to the peer */
1076
                                        send(session->media.audio_rtp_fd, buf, len, 0);
1077
                                }
1078
                        }
1079
                }
1080
        }
1081
}
1082

    
1083
void janus_sip_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
1084
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1085
                return;
1086
        if(gateway) {
1087
                janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1088
                if(!session || session->destroyed) {
1089
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1090
                        return;
1091
                }
1092
                if(session->status != janus_sip_call_status_incall)
1093
                        return;
1094
                /* Forward to our SIP peer */
1095
                if(video) {
1096
                        if(session->media.has_video && session->media.video_rtcp_fd) {
1097
                                /* Is SRTP involved? */
1098
                                if(session->media.has_srtp_local) {
1099
                                        char sbuf[2048];
1100
                                        memcpy(&sbuf, buf, len);
1101
                                        int protected = len;
1102
                                        int res = srtp_protect_rtcp(session->media.video_srtp_out, &sbuf, &protected);
1103
                                        if(res != err_status_ok) {
1104
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTCP protect error... %s (len=%d-->%d)...\n",
1105
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected);
1106
                                        } else {
1107
                                                /* Fix SSRCs as the gateway does */
1108
                                                JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1109
                                                        session->media.video_ssrc, session->media.video_ssrc_peer);
1110
                                                janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.video_ssrc, session->media.video_ssrc_peer);
1111
                                                /* Forward the message to the peer */
1112
                                                send(session->media.video_rtcp_fd, sbuf, protected, 0);
1113
                                        }
1114
                                } else {
1115
                                        /* Fix SSRCs as the gateway does */
1116
                                        JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1117
                                                session->media.video_ssrc, session->media.video_ssrc_peer);
1118
                                        janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.video_ssrc, session->media.video_ssrc_peer);
1119
                                        /* Forward the message to the peer */
1120
                                        send(session->media.video_rtcp_fd, buf, len, 0);
1121
                                }
1122
                        }
1123
                } else {
1124
                        if(session->media.has_audio && session->media.audio_rtcp_fd) {
1125
                                /* Is SRTP involved? */
1126
                                if(session->media.has_srtp_local) {
1127
                                        char sbuf[2048];
1128
                                        memcpy(&sbuf, buf, len);
1129
                                        int protected = len;
1130
                                        int res = srtp_protect_rtcp(session->media.audio_srtp_out, &sbuf, &protected);
1131
                                        if(res != err_status_ok) {
1132
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTCP protect error... %s (len=%d-->%d)...\n",
1133
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected);
1134
                                        } else {
1135
                                                /* Fix SSRCs as the gateway does */
1136
                                                JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1137
                                                        session->media.audio_ssrc, session->media.audio_ssrc_peer);
1138
                                                janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.audio_ssrc, session->media.audio_ssrc_peer);
1139
                                                /* Forward the message to the peer */
1140
                                                send(session->media.audio_rtcp_fd, sbuf, protected, 0);
1141
                                        }
1142
                                } else {
1143
                                        /* Fix SSRCs as the gateway does */
1144
                                        JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1145
                                                session->media.audio_ssrc, session->media.audio_ssrc_peer);
1146
                                        janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.audio_ssrc, session->media.audio_ssrc_peer);
1147
                                        /* Forward the message to the peer */
1148
                                        send(session->media.audio_rtcp_fd, buf, len, 0);
1149
                                }
1150
                        }
1151
                }
1152
        }
1153
}
1154

    
1155
void janus_sip_hangup_media(janus_plugin_session *handle) {
1156
        JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
1157
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1158
                return;
1159
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1160
        if(!session) {
1161
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1162
                return;
1163
        }
1164
        if(session->destroyed)
1165
                return;
1166
        if(g_atomic_int_add(&session->hangingup, 1))
1167
                return;
1168
        if(!(session->status == janus_sip_call_status_inviting ||
1169
                 session->status == janus_sip_call_status_invited ||
1170
                 session->status == janus_sip_call_status_incall))
1171
                return;
1172
        /* Get rid of the recorders, if available */
1173
        janus_mutex_lock(&session->rec_mutex);
1174
        if(session->arc) {
1175
                janus_recorder_close(session->arc);
1176
                JANUS_LOG(LOG_INFO, "Closed user's audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
1177
                janus_recorder_free(session->arc);
1178
        }
1179
        session->arc = NULL;
1180
        if(session->arc_peer) {
1181
                janus_recorder_close(session->arc_peer);
1182
                JANUS_LOG(LOG_INFO, "Closed peer's audio recording %s\n", session->arc_peer->filename ? session->arc_peer->filename : "??");
1183
                janus_recorder_free(session->arc_peer);
1184
        }
1185
        session->arc_peer = NULL;
1186
        if(session->vrc) {
1187
                janus_recorder_close(session->vrc);
1188
                JANUS_LOG(LOG_INFO, "Closed user's video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
1189
                janus_recorder_free(session->vrc);
1190
        }
1191
        session->vrc = NULL;
1192
        if(session->vrc_peer) {
1193
                janus_recorder_close(session->vrc_peer);
1194
                JANUS_LOG(LOG_INFO, "Closed peer's video recording %s\n", session->vrc_peer->filename ? session->vrc_peer->filename : "??");
1195
                janus_recorder_free(session->vrc_peer);
1196
        }
1197
        session->vrc_peer = NULL;
1198
        janus_mutex_unlock(&session->rec_mutex);
1199
        /* FIXME Simulate a "hangup" coming from the browser */
1200
        janus_sip_message *msg = g_malloc0(sizeof(janus_sip_message));
1201
        msg->handle = handle;
1202
        msg->message = g_strdup("{\"request\":\"hangup\"}");
1203
        msg->transaction = NULL;
1204
        msg->sdp_type = NULL;
1205
        msg->sdp = NULL;
1206
        g_async_queue_push(messages, msg);
1207
}
1208

    
1209
/* Thread to handle incoming messages */
1210
static void *janus_sip_handler(void *data) {
1211
        JANUS_LOG(LOG_VERB, "Joining SIP handler thread\n");
1212
        janus_sip_message *msg = NULL;
1213
        int error_code = 0;
1214
        char error_cause[512];
1215
        json_t *root = NULL;
1216
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
1217
                msg = g_async_queue_pop(messages);
1218
                if(msg == NULL)
1219
                        continue;
1220
                if(msg == &exit_message)
1221
                        break;
1222
                if(msg->handle == NULL) {
1223
                        janus_sip_message_free(msg);
1224
                        continue;
1225
                }
1226
                janus_sip_session *session = NULL;
1227
                janus_mutex_lock(&sessions_mutex);
1228
                if(g_hash_table_lookup(sessions, msg->handle) != NULL ) {
1229
                        session = (janus_sip_session *)msg->handle->plugin_handle;
1230
                }
1231
                janus_mutex_unlock(&sessions_mutex);
1232
                if(!session) {
1233
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1234
                        janus_sip_message_free(msg);
1235
                        continue;
1236
                }
1237
                if(session->destroyed) {
1238
                        janus_sip_message_free(msg);
1239
                        continue;
1240
                }
1241
                /* Handle request */
1242
                error_code = 0;
1243
                root = NULL;
1244
                JANUS_LOG(LOG_VERB, "Handling message: %s\n", msg->message);
1245
                if(msg->message == NULL) {
1246
                        JANUS_LOG(LOG_ERR, "No message??\n");
1247
                        error_code = JANUS_SIP_ERROR_NO_MESSAGE;
1248
                        g_snprintf(error_cause, 512, "%s", "No message??");
1249
                        goto error;
1250
                }
1251
                json_error_t error;
1252
                root = json_loads(msg->message, 0, &error);
1253
                if(!root) {
1254
                        JANUS_LOG(LOG_ERR, "JSON error: on line %d: %s\n", error.line, error.text);
1255
                        error_code = JANUS_SIP_ERROR_INVALID_JSON;
1256
                        g_snprintf(error_cause, 512, "JSON error: on line %d: %s", error.line, error.text);
1257
                        goto error;
1258
                }
1259
                if(!json_is_object(root)) {
1260
                        JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
1261
                        error_code = JANUS_SIP_ERROR_INVALID_JSON;
1262
                        g_snprintf(error_cause, 512, "JSON error: not an object");
1263
                        goto error;
1264
                }
1265
                JANUS_VALIDATE_JSON_OBJECT(root, request_parameters,
1266
                        error_code, error_cause, TRUE,
1267
                        JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1268
                if(error_code != 0)
1269
                        goto error;
1270
                json_t *request = json_object_get(root, "request");
1271
                const char *request_text = json_string_value(request);
1272
                json_t *result = NULL;
1273
                char *sdp_type = NULL, *sdp = NULL;
1274

    
1275
                if(!strcasecmp(request_text, "register")) {
1276
                        /* Send a REGISTER */
1277
                        if(session->account.registration_status > janus_sip_registration_status_unregistered) {
1278
                                JANUS_LOG(LOG_ERR, "Already registered (%s)\n", session->account.username);
1279
                                error_code = JANUS_SIP_ERROR_ALREADY_REGISTERED;
1280
                                g_snprintf(error_cause, 512, "Already registered (%s)", session->account.username);
1281
                                goto error;
1282
                        }
1283

    
1284
                        /* Cleanup old values */
1285
                        if(session->account.identity != NULL)
1286
                                g_free(session->account.identity);
1287
                        session->account.identity = NULL;
1288
                        session->account.sips = TRUE;
1289
                        if(session->account.username != NULL)
1290
                                g_free(session->account.username);
1291
                        session->account.username = NULL;
1292
                        if(session->account.display_name != NULL)
1293
                                g_free(session->account.display_name);
1294
                        session->account.display_name = NULL;
1295
                        if(session->account.authuser != NULL)
1296
                                g_free(session->account.authuser);
1297
                        session->account.authuser = NULL;
1298
                        if(session->account.secret != NULL)
1299
                                g_free(session->account.secret);
1300
                        session->account.secret = NULL;
1301
                        session->account.secret_type = janus_sip_secret_type_unknown;
1302
                        if(session->account.proxy != NULL)
1303
                                g_free(session->account.proxy);
1304
                        session->account.proxy = NULL;
1305
                        if(session->account.user_agent != NULL)
1306
                                g_free(session->account.user_agent);
1307
                        session->account.user_agent = NULL;
1308
                        session->account.registration_status = janus_sip_registration_status_unregistered;
1309

    
1310
                        gboolean guest = FALSE;
1311
                        JANUS_VALIDATE_JSON_OBJECT(root, register_parameters,
1312
                                error_code, error_cause, TRUE,
1313
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1314
                        if(error_code != 0)
1315
                                goto error;
1316
                        json_t *type = json_object_get(root, "type");
1317
                        if(type != NULL) {
1318
                                const char *type_text = json_string_value(type);
1319
                                if(!strcmp(type_text, "guest")) {
1320
                                        JANUS_LOG(LOG_INFO, "Registering as a guest\n");
1321
                                        guest = TRUE;
1322
                                } else {
1323
                                        JANUS_LOG(LOG_WARN, "Unknown type '%s', ignoring...\n", type_text);
1324
                                }
1325
                        }
1326

    
1327
                        gboolean send_register = TRUE;
1328
                        json_t *do_register = json_object_get(root, "send_register");
1329
                        if(do_register != NULL) {
1330
                                if(guest) {
1331
                                        JANUS_LOG(LOG_ERR, "Conflicting elements: send_register cannot be true if guest is true\n");
1332
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1333
                                        g_snprintf(error_cause, 512, "Conflicting elements: send_register cannot be true if guest is true");
1334
                                        goto error;
1335
                                }
1336
                                send_register = json_is_true(do_register);
1337
                        }
1338

    
1339
                        gboolean sips = TRUE;
1340
                        json_t *do_sips = json_object_get(root, "sips");
1341
                        if(do_sips != NULL) {
1342
                                sips = json_is_true(do_sips);
1343
                        }
1344

    
1345
                        /* Parse address */
1346
                        json_t *proxy = json_object_get(root, "proxy");
1347
                        const char *proxy_text = NULL;
1348

    
1349
                        if (proxy && !json_is_null(proxy)) {
1350
                                /* Has to be validated separately because it could be null */
1351
                                JANUS_VALIDATE_JSON_OBJECT(root, proxy_parameters,
1352
                                        error_code, error_cause, TRUE,
1353
                                        JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1354
                                if(error_code != 0)
1355
                                        goto error;
1356
                                proxy_text = json_string_value(proxy);
1357
                                janus_sip_uri_t proxy_uri;
1358
                                if (janus_sip_parse_proxy_uri(&proxy_uri, proxy_text) < 0) {
1359
                                        JANUS_LOG(LOG_ERR, "Invalid proxy address %s\n", proxy_text);
1360
                                        error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1361
                                        g_snprintf(error_cause, 512, "Invalid proxy address %s\n", proxy_text);
1362
                                        goto error;
1363
                                }
1364
                        }
1365

    
1366
                        /* Parse register TTL */
1367
                        int ttl = register_ttl;
1368
                        json_t *reg_ttl = json_object_get(root, "register_ttl");
1369
                        if (reg_ttl && json_is_integer(reg_ttl))
1370
                                ttl = json_integer_value(reg_ttl);
1371
                        if (ttl <= 0)
1372
                                ttl = JANUS_DEFAULT_REGISTER_TTL;
1373

    
1374
                        /* Parse display name */
1375
                        const char* display_name_text = NULL;
1376
                        json_t *display_name = json_object_get(root, "display_name");
1377
                        if (display_name && json_is_string(display_name))
1378
                                display_name_text = json_string_value(display_name);
1379

    
1380
                        /* Parse user agent */
1381
                        const char* user_agent_text = NULL;
1382
                        json_t *user_agent = json_object_get(root, "user_agent");
1383
                        if (user_agent && json_is_string(user_agent))
1384
                                user_agent_text = json_string_value(user_agent);
1385

    
1386
                        /* Now the user part, if needed */
1387
                        json_t *username = json_object_get(root, "username");
1388
                        if(!guest && !username) {
1389
                                /* The username is mandatory if we're not registering as guests */
1390
                                JANUS_LOG(LOG_ERR, "Missing element (username)\n");
1391
                                error_code = JANUS_SIP_ERROR_MISSING_ELEMENT;
1392
                                g_snprintf(error_cause, 512, "Missing element (username)");
1393
                                goto error;
1394
                        }
1395
                        const char *username_text = NULL;
1396
                        janus_sip_uri_t username_uri;
1397
                        char user_id[256];
1398
                        if(username) {
1399
                                /* Parse address */
1400
                                username_text = json_string_value(username);
1401
                                if (janus_sip_parse_uri(&username_uri, username_text) < 0) {
1402
                                        JANUS_LOG(LOG_ERR, "Invalid user address %s\n", username_text);
1403
                                        error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1404
                                        g_snprintf(error_cause, 512, "Invalid user address %s\n", username_text);
1405
                                        goto error;
1406
                                }
1407
                                g_strlcpy(user_id, username_uri.url->url_user, sizeof(user_id));
1408
                        }
1409
                        if(guest) {
1410
                                /* Not needed, we can stop here: just pick a random username if it wasn't provided and say we're registered */
1411
                                if(!username)
1412
                                        g_snprintf(user_id, 255, "janus-sip-%"SCNu32"", g_random_int());
1413
                                JANUS_LOG(LOG_INFO, "Guest will have username %s\n", user_id);
1414
                                send_register = FALSE;
1415
                        } else {
1416
                                json_t *secret = json_object_get(root, "secret");
1417
                                json_t *ha1_secret = json_object_get(root, "ha1_secret");
1418
                                json_t *authuser = json_object_get(root, "authuser");
1419
                                if(!secret && !ha1_secret) {
1420
                                        JANUS_LOG(LOG_ERR, "Missing element (secret or ha1_secret)\n");
1421
                                        error_code = JANUS_SIP_ERROR_MISSING_ELEMENT;
1422
                                        g_snprintf(error_cause, 512, "Missing element (secret or ha1_secret)");
1423
                                        goto error;
1424
                                }
1425
                                if(secret && ha1_secret) {
1426
                                        JANUS_LOG(LOG_ERR, "Conflicting elements specified (secret and ha1_secret)\n");
1427
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1428
                                        g_snprintf(error_cause, 512, "Conflicting elements specified (secret and ha1_secret)");
1429
                                        goto error;
1430
                                }
1431
                                const char *secret_text;
1432
                                if(secret) {
1433
                                        secret_text = json_string_value(secret);
1434
                                        session->account.secret = g_strdup(secret_text);
1435
                                        session->account.secret_type = janus_sip_secret_type_plaintext;
1436
                                } else {
1437
                                        secret_text = json_string_value(ha1_secret);
1438
                                        session->account.secret = g_strdup(secret_text);
1439
                                        session->account.secret_type = janus_sip_secret_type_hashed;
1440
                                }
1441
                                if (authuser) {
1442
                                        const char *authuser_text;
1443
                                        authuser_text = json_string_value(authuser);
1444
                                        session->account.authuser = g_strdup(authuser_text);
1445
                                } else {
1446
                                        session->account.authuser = g_strdup(user_id);
1447
                                }
1448
                                /* Got the values, try registering now */
1449
                                JANUS_LOG(LOG_VERB, "Registering user %s (secret %s) @ %s through %s\n",
1450
                                        username_text, secret_text, username_uri.url->url_host, proxy_text != NULL ? proxy_text : "(null)");
1451
                        }
1452

    
1453
                        session->account.identity = g_strdup(username_text);
1454
                        session->account.sips = sips;
1455
                        session->account.username = g_strdup(user_id);
1456
                        if (display_name_text) {
1457
                                session->account.display_name = g_strdup(display_name_text);
1458
                        }
1459
                        if (user_agent_text) {
1460
                                session->account.user_agent = g_strdup(user_agent_text);
1461
                        }
1462
                        if (proxy_text) {
1463
                                session->account.proxy = g_strdup(proxy_text);
1464
                        }
1465

    
1466
                        session->account.registration_status = janus_sip_registration_status_registering;
1467
                        if(session->stack == NULL) {
1468
                                /* Start the thread first */
1469
                                GError *error = NULL;
1470
                                g_thread_try_new("worker", janus_sip_sofia_thread, session, &error);
1471
                                if(error != NULL) {
1472
                                        JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP Sofia thread...\n", error->code, error->message ? error->message : "??");
1473
                                        error_code = JANUS_SIP_ERROR_UNKNOWN_ERROR;
1474
                                        g_snprintf(error_cause, 512, "Got error %d (%s) trying to launch the SIP Sofia thread", error->code, error->message ? error->message : "??");
1475
                                        goto error;
1476
                                }
1477
                                long int timeout = 0;
1478
                                while(session->stack == NULL || session->stack->s_nua == NULL) {
1479
                                        g_usleep(100000);
1480
                                        timeout += 100000;
1481
                                        if(timeout >= 2000000) {
1482
                                                break;
1483
                                        }
1484
                                }
1485
                                if(timeout >= 2000000) {
1486
                                        JANUS_LOG(LOG_ERR, "Two seconds passed and still no NUA, problems with the thread?\n");
1487
                                        error_code = JANUS_SIP_ERROR_UNKNOWN_ERROR;
1488
                                        g_snprintf(error_cause, 512, "Two seconds passed and still no NUA, problems with the thread?");
1489
                                        goto error;
1490
                                }
1491
                        }
1492
                        if(session->stack->s_nh_r != NULL) {
1493
                                nua_handle_destroy(session->stack->s_nh_r);
1494
                                session->stack->s_nh_r = NULL;
1495
                        }
1496

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

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

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

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

    
2166

    
2167
/* Sofia callbacks */
2168
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[])
2169
{
2170
        janus_sip_session *session = (janus_sip_session *)magic;
2171
        ssip_t *ssip = session->stack;
2172
        switch (event) {
2173
        /* Status or Error Indications */
2174
                case nua_i_active:
2175
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2176
                        break;
2177
                case nua_i_error:
2178
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2179
                        break;
2180
                case nua_i_fork:
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_media_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_subscription:
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_state:
2190
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2191
                        tagi_t const *ti = tl_find(tags, nutag_callstate);
2192
                        enum nua_callstate callstate = ti ? ti->t_value : -1;
2193
                        /* There are several call states, but we care about the terminated state in order to send the 'hangup' event
2194
                         * and the proceeding state in order to send the 'proceeding' event so the client can play a ringback tone for 
2195
                         * the user since we don't send early media. (assuming this is the right session, of course).
2196
                         * http://sofia-sip.sourceforge.net/refdocs/nua/nua__tag_8h.html#a516dc237722dc8ca4f4aa3524b2b444b
2197
                         */
2198
                        if (callstate == nua_callstate_proceeding && 
2199
                                    (session->stack->s_nh_i == nh || session->stack->s_nh_i == NULL)) {
2200
                                json_t *call = json_object();
2201
                                json_object_set_new(call, "sip", json_string("event"));
2202
                                json_t *calling = json_object();
2203
                                json_object_set_new(calling, "event", json_string("proceeding"));
2204
                                json_object_set_new(calling, "code", json_integer(status));
2205
                                json_object_set_new(call, "result", calling);
2206
                                char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2207
                                json_decref(call);
2208
                                JANUS_LOG(LOG_VERB, "Pushing event: %s\n", call_text);
2209
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call_text, NULL, NULL);
2210
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2211
                                g_free(call_text);
2212
                        } else if(callstate == nua_callstate_terminated &&
2213
                                        (session->stack->s_nh_i == nh || session->stack->s_nh_i == NULL)) {
2214
                                session->status = janus_sip_call_status_idle;
2215
                                session->stack->s_nh_i = NULL;
2216
                                json_t *call = json_object();
2217
                                json_object_set_new(call, "sip", json_string("event"));
2218
                                json_t *calling = json_object();
2219
                                json_object_set_new(calling, "event", json_string("hangup"));
2220
                                json_object_set_new(calling, "code", json_integer(status));
2221
                                json_object_set_new(calling, "reason", json_string(phrase ? phrase : "???"));
2222
                                json_object_set_new(call, "result", calling);
2223
                                char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2224
                                json_decref(call);
2225
                                JANUS_LOG(LOG_VERB, "Pushing event: %s\n", call_text);
2226
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call_text, NULL, NULL);
2227
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2228
                                g_free(call_text);
2229
                                /* Get rid of any PeerConnection that may have been set up */
2230
                                if(session->transaction)
2231
                                        g_free(session->transaction);
2232
                                session->transaction = NULL;
2233
                                gateway->close_pc(session->handle);
2234
                        }
2235
                        break;
2236
                case nua_i_terminated:
2237
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2238
                        break;
2239
        /* SIP requests */
2240
                case nua_i_ack:
2241
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2242
                        break;
2243
                case nua_i_outbound:
2244
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2245
                        break;
2246
                case nua_i_bye: {
2247
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2248
                        break;
2249
                }
2250
                case nua_i_cancel: {
2251
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2252
                        break;
2253
                }
2254
                case nua_i_invite: {
2255
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2256
                        if(ssip == NULL) {
2257
                                JANUS_LOG(LOG_ERR, "\tInvalid SIP stack\n");
2258
                                nua_respond(nh, 500, sip_status_phrase(500), TAG_END());
2259
                                break;
2260
                        }
2261
                        sdp_parser_t *parser = sdp_parse(ssip->s_home, sip->sip_payload->pl_data, sip->sip_payload->pl_len, 0);
2262
                        if(!sdp_session(parser)) {
2263
                                JANUS_LOG(LOG_ERR, "\tError parsing SDP!\n");
2264
                                nua_respond(nh, 488, sip_status_phrase(488), TAG_END());
2265
                                sdp_parser_free(parser);
2266
                                break;
2267
                        }
2268
                        if(session->stack->s_nh_i != NULL) {
2269
                                if(session->stack->s_nh_i == nh) {
2270
                                        /* re-INVITE, we don't support those. */
2271
                                        nua_respond(nh, 488, sip_status_phrase(488), TAG_END());
2272
                                } else if(session->status >= janus_sip_call_status_inviting) {
2273
                                        /* Busy with another call */
2274
                                        JANUS_LOG(LOG_VERB, "\tAlready in a call (busy, status=%s)\n", janus_sip_call_status_string(session->status));
2275
                                        nua_respond(nh, 486, sip_status_phrase(486), TAG_END());
2276
                                        /* Notify the web app about the missed invite */
2277
                                        json_t *missed = json_object();
2278
                                        json_object_set_new(missed, "sip", json_string("event"));
2279
                                        json_t *result = json_object();
2280
                                        json_object_set_new(result, "event", json_string("missed_call"));
2281
                                        char *caller_text = url_as_string(session->stack->s_home, sip->sip_from->a_url);
2282
                                        json_object_set_new(result, "caller", json_string(caller_text));
2283
                                        su_free(session->stack->s_home, caller_text);
2284
                                        if (sip->sip_from && sip->sip_from->a_display) {
2285
                                                json_object_set_new(result, "displayname", json_string(sip->sip_from->a_display));
2286
                                        }
2287
                                        json_object_set_new(missed, "result", result);
2288
                                        char *missed_text = json_dumps(missed, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2289
                                        json_decref(missed);
2290
                                        JANUS_LOG(LOG_VERB, "Pushing event to peer: %s\n", missed_text);
2291
                                        int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, missed_text, NULL, NULL);
2292
                                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2293
                                        g_free(missed_text);
2294
                                }
2295
                                sdp_parser_free(parser);
2296
                                break;
2297
                        }
2298
                        /* New incoming call */
2299
                        session->callee = g_strdup(url_as_string(session->stack->s_home, sip->sip_from->a_url));
2300
                        session->status = janus_sip_call_status_invited;
2301
                        /* Clean up SRTP stuff from before first, in case it's still needed */
2302
                        janus_sip_srtp_cleanup(session);
2303
                        /* Parse SDP */
2304
                        char *fixed_sdp = g_strdup(sip->sip_payload->pl_data);
2305
                        JANUS_LOG(LOG_VERB, "Someone is inviting us in a call:\n%s", sip->sip_payload->pl_data);
2306
                        sdp_session_t *sdp = sdp_session(parser);
2307
                        janus_sip_sdp_process(session, sdp, FALSE);
2308
                        /* Send SDP to the browser */
2309
                        json_t *call = json_object();
2310
                        json_object_set_new(call, "sip", json_string("event"));
2311
                        json_t *calling = json_object();
2312
                        json_object_set_new(calling, "event", json_string("incomingcall"));
2313
                        json_object_set_new(calling, "username", json_string(session->callee));
2314
                        if(sip->sip_from && sip->sip_from->a_display) {
2315
                                json_object_set_new(calling, "displayname", json_string(sip->sip_from->a_display));
2316
                        }
2317
                        if(session->media.has_srtp_remote) {
2318
                                /* FIXME Maybe a true/false instead? */
2319
                                json_object_set_new(calling, "srtp", json_string(session->media.require_srtp ? "sdes_mandatory" : "sdes_optional"));
2320
                        }
2321
                        json_object_set_new(call, "result", calling);
2322
                        char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2323
                        json_decref(call);
2324
                        JANUS_LOG(LOG_VERB, "Pushing event to peer: %s\n", call_text);
2325
                        int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call_text, "offer", fixed_sdp);
2326
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2327
                        g_free(call_text);
2328
                        g_free(fixed_sdp);
2329
                        /* Send a Ringing back */
2330
                        nua_respond(nh, 180, sip_status_phrase(180), TAG_END());
2331
                        session->stack->s_nh_i = nh;
2332
                        break;
2333
                }
2334
                case nua_i_options:
2335
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2336
                        /* FIXME Should we handle this message? for now we reply with a 405 Method Not Implemented */
2337
                        nua_respond(nh, 405, sip_status_phrase(405), TAG_END());
2338
                        break;
2339
        /* Responses */
2340
                case nua_r_get_params:
2341
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2342
                        break;
2343
                case nua_r_set_params:
2344
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2345
                        break;
2346
                case nua_r_notifier:
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_shutdown:
2350
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2351
                        if(status < 200 && !g_atomic_int_get(&stopping)) {
2352
                                /* shutdown in progress -> return */
2353
                                break;
2354
                        }
2355
                        if(ssip != NULL) {
2356
                                /* end the event loop. su_root_run() will return */
2357
                                su_root_break(ssip->s_root);
2358
                        }
2359
                        break;
2360
                case nua_r_terminate:
2361
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2362
                        break;
2363
        /* SIP responses */
2364
                case nua_r_bye:
2365
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2366
                        break;
2367
                case nua_r_cancel:
2368
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2369
                        break;
2370
                case nua_r_info:
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_invite: {
2374
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2375
                        
2376
                        if(status < 200) {
2377
                                /* Not ready yet (FIXME May this be pranswer?? we don't handle it yet...) */
2378
                                break;
2379
                        } else if(status == 401 || status == 407) {
2380
                                char auth[256];
2381
                                const char* scheme;
2382
                                const char* realm;
2383
                                if(status == 401) {
2384
                                         /* Get scheme/realm from 401 error */
2385
                                        sip_www_authenticate_t const* www_auth = sip->sip_www_authenticate;
2386
                                        scheme = www_auth->au_scheme;
2387
                                        realm = msg_params_find(www_auth->au_params, "realm=");
2388
                                } else {
2389
                                         /* Get scheme/realm from 407 error, proxy-auth */
2390
                                        sip_proxy_authenticate_t const* proxy_auth = sip->sip_proxy_authenticate;
2391
                                        scheme = proxy_auth->au_scheme;
2392
                                        realm = msg_params_find(proxy_auth->au_params, "realm=");
2393
                                }
2394
                                memset(auth, 0, sizeof(auth));
2395
                                g_snprintf(auth, sizeof(auth), "%s%s:%s:%s:%s%s",
2396
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
2397
                                        scheme,
2398
                                        realm,
2399
                                        session->account.authuser ? session->account.authuser : "null",
2400
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
2401
                                        session->account.secret ? session->account.secret : "null");
2402
                                JANUS_LOG(LOG_VERB, "\t%s\n", auth);
2403
                                /* Authenticate */
2404
                                nua_authenticate(nh,
2405
                                        NUTAG_AUTH(auth),
2406
                                        TAG_END());
2407
                                break;
2408
                        } else if(status >= 400) {
2409
                                break;
2410
                        }
2411
                        if(ssip == NULL) {
2412
                                JANUS_LOG(LOG_ERR, "\tInvalid SIP stack\n");
2413
                                nua_respond(nh, 500, sip_status_phrase(500), TAG_END());
2414
                                break;
2415
                        }
2416
                        sdp_parser_t *parser = sdp_parse(ssip->s_home, sip->sip_payload->pl_data, sip->sip_payload->pl_len, 0);
2417
                        if(!sdp_session(parser)) {
2418
                                JANUS_LOG(LOG_ERR, "\tError parsing SDP!\n");
2419
                                nua_respond(nh, 488, sip_status_phrase(488), TAG_END());
2420
                                sdp_parser_free(parser);
2421
                                break;
2422
                        }
2423
                        /* Send an ACK */
2424
                        char *route = sip->sip_record_route ? url_as_string(session->stack->s_home, sip->sip_record_route->r_url) : NULL;
2425
                        JANUS_LOG(LOG_WARN, "Sending ACK (route=%s)\n", route ? route : "none");
2426
                        nua_ack(nh,
2427
                                TAG_IF(route, NTATAG_DEFAULT_PROXY(route)),
2428
                                TAG_END());
2429
                        /* Parse SDP */
2430
                        JANUS_LOG(LOG_VERB, "Peer accepted our call:\n%s", sip->sip_payload->pl_data);
2431
                        session->status = janus_sip_call_status_incall;
2432
                        char *fixed_sdp = g_strdup(sip->sip_payload->pl_data);
2433
                        sdp_session_t *sdp = sdp_session(parser);
2434
                        janus_sip_sdp_process(session, sdp, TRUE);
2435
                        /* If we asked for SRTP and are not getting it, fail */
2436
                        if(session->media.require_srtp && !session->media.has_srtp_remote) {
2437
                                JANUS_LOG(LOG_ERR, "\tWe asked for mandatory SRTP but didn't get any in the reply!\n");
2438
                                sdp_parser_free(parser);
2439
                                g_free(fixed_sdp);
2440
                                /* Hangup immediately */
2441
                                session->status = janus_sip_call_status_closing;
2442
                                nua_bye(nh, TAG_END());
2443
                                g_free(session->callee);
2444
                                session->callee = NULL;
2445
                                break;
2446
                        }
2447
                        if(session->media.audio_pt > -1) {
2448
                                session->media.audio_pt_name = janus_get_codec_from_pt(fixed_sdp, session->media.audio_pt);
2449
                                JANUS_LOG(LOG_VERB, "Detected audio codec: %d (%s)\n", session->media.audio_pt, session->media.audio_pt_name);
2450
                        }
2451
                        if(session->media.video_pt > -1) {
2452
                                session->media.video_pt_name = janus_get_codec_from_pt(fixed_sdp, session->media.video_pt);
2453
                                JANUS_LOG(LOG_VERB, "Detected video codec: %d (%s)\n", session->media.video_pt, session->media.video_pt_name);
2454
                        }
2455
                        session->media.ready = 1;        /* FIXME Maybe we need a better way to signal this */
2456
                        GError *error = NULL;
2457
                        g_thread_try_new("janus rtp handler", janus_sip_relay_thread, session, &error);
2458
                        if(error != NULL) {
2459
                                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the RTP/RTCP thread...\n", error->code, error->message ? error->message : "??");
2460
                        }
2461
                        /* Send SDP to the browser */
2462
                        json_t *call = json_object();
2463
                        json_object_set_new(call, "sip", json_string("event"));
2464
                        json_t *calling = json_object();
2465
                        json_object_set_new(calling, "event", json_string("accepted"));
2466
                        json_object_set_new(calling, "username", json_string(session->callee));
2467
                        json_object_set_new(call, "result", calling);
2468
                        char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2469
                        json_decref(call);
2470
                        JANUS_LOG(LOG_VERB, "Pushing event to peer: %s\n", call_text);
2471
                        int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call_text, "answer", fixed_sdp);
2472
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2473
                        g_free(call_text);
2474
                        g_free(fixed_sdp);
2475
                        break;
2476
                }
2477
                case nua_r_register: {
2478
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2479
                        if(status == 200) {
2480
                                if(session->account.registration_status < janus_sip_registration_status_registered)
2481
                                        session->account.registration_status = janus_sip_registration_status_registered;
2482
                                JANUS_LOG(LOG_VERB, "Successfully registered\n");
2483
                                /* Notify the browser */
2484
                                json_t *call = json_object();
2485
                                json_object_set_new(call, "sip", json_string("event"));
2486
                                json_t *calling = json_object();
2487
                                json_object_set_new(calling, "event", json_string("registered"));
2488
                                json_object_set_new(calling, "username", json_string(session->account.username));
2489
                                json_object_set_new(calling, "register_sent", json_string("true"));
2490
                                json_object_set_new(call, "result", calling);
2491
                                char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2492
                                json_decref(call);
2493
                                JANUS_LOG(LOG_VERB, "Pushing event: %s\n", call_text);
2494
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call_text, NULL, NULL);
2495
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2496
                                g_free(call_text);
2497
                        } else if(status == 401) {
2498
                                /* Get scheme/realm from 401 error */
2499
                                sip_www_authenticate_t const* www_auth = sip->sip_www_authenticate;
2500
                                char const* scheme = www_auth->au_scheme;
2501
                                const char* realm = msg_params_find(www_auth->au_params, "realm=");
2502
                                char auth[256];
2503
                                memset(auth, 0, sizeof(auth));
2504
                                g_snprintf(auth, sizeof(auth), "%s%s:%s:%s:%s%s",
2505
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
2506
                                        scheme,
2507
                                        realm,
2508
                                        session->account.authuser ? session->account.authuser : "null",
2509
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
2510
                                        session->account.secret);
2511
                                JANUS_LOG(LOG_VERB, "\t%s\n", auth);
2512
                                /* Authenticate */
2513
                                nua_authenticate(nh,
2514
                                        NUTAG_AUTH(auth),
2515
                                        TAG_END());
2516
                        } else if(status >= 400) {
2517
                                /* Authentication failed? */
2518
                                session->account.registration_status = janus_sip_registration_status_failed;
2519
                                /* Tell the browser... */
2520
                                json_t *event = json_object();
2521
                                json_object_set_new(event, "sip", json_string("event"));
2522
                                json_t *result = json_object();
2523
                                json_object_set_new(result, "event", json_string("registration_failed"));
2524
                                json_object_set_new(result, "code", json_integer(status));
2525
                                json_object_set_new(result, "reason", json_string(phrase ? phrase : ""));
2526
                                json_object_set_new(event, "result", result);
2527
                                char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2528
                                json_decref(event);
2529
                                JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
2530
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, event_text, NULL, NULL);
2531
                                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2532
                                g_free(event_text);
2533
                        }
2534
                        break;
2535
                }
2536
                default:
2537
                        /* unknown event -> print out error message */
2538
                        JANUS_LOG(LOG_ERR, "Unknown event %d (%s)\n", event, nua_event_name(event));
2539
                        break;
2540
        }
2541
}
2542

    
2543
void janus_sip_sdp_process(janus_sip_session *session, sdp_session_t *sdp, gboolean answer) {
2544
        if(!session || !sdp)
2545
                return;
2546
        /* c= */
2547
        if(sdp->sdp_connection && sdp->sdp_connection->c_address) {
2548
                g_free(session->media.remote_ip);
2549
                session->media.remote_ip = g_strdup(sdp->sdp_connection->c_address);
2550
                JANUS_LOG(LOG_VERB, "  >> Media connection:\n");
2551
                JANUS_LOG(LOG_VERB, "       %s\n", session->media.remote_ip);
2552
        }
2553
        JANUS_LOG(LOG_VERB, "  >> Media lines:\n");
2554
        sdp_media_t *m = sdp->sdp_media;
2555
        while(m) {
2556
                session->media.require_srtp = session->media.require_srtp || (m->m_proto_name && !strcasecmp(m->m_proto_name, "RTP/SAVP"));
2557
                if(m->m_type == sdp_media_audio) {
2558
                        JANUS_LOG(LOG_VERB, "       Audio: %lu\n", m->m_port);
2559
                        if(m->m_port) {
2560
                                session->media.has_audio = 1;
2561
                                session->media.remote_audio_rtp_port = m->m_port;
2562
                                session->media.remote_audio_rtcp_port = m->m_port+1;        /* FIXME We're assuming RTCP is on the next port */
2563
                        }
2564
                } else if(m->m_type == sdp_media_video) {
2565
                        JANUS_LOG(LOG_VERB, "       Video: %lu\n", m->m_port);
2566
                        if(m->m_port) {
2567
                                session->media.has_video = 1;
2568
                                session->media.remote_video_rtp_port = m->m_port;
2569
                                session->media.remote_video_rtcp_port = m->m_port+1;        /* FIXME We're assuming RTCP is on the next port */
2570
                        }
2571
                } else {
2572
                        JANUS_LOG(LOG_WARN, "       Unsupported media line (not audio/video)\n");
2573
                        m = m->m_next;
2574
                        continue;
2575
                }
2576
                JANUS_LOG(LOG_VERB, "       Media connections:\n");
2577
                if(m->m_connections) {
2578
                        sdp_connection_t *c = m->m_connections;
2579
                        while(c) {
2580
                                if(c->c_address) {
2581
                                        g_free(session->media.remote_ip);
2582
                                        session->media.remote_ip = g_strdup(c->c_address);
2583
                                        JANUS_LOG(LOG_VERB, "         [%s]\n", session->media.remote_ip);
2584
                                }
2585
                                c = c->c_next;
2586
                        }
2587
                }
2588
                JANUS_LOG(LOG_VERB, "       Media RTP maps:\n");
2589
                sdp_rtpmap_t *r = m->m_rtpmaps;
2590
                while(r) {
2591
                        JANUS_LOG(LOG_VERB, "         [%u] %s\n", r->rm_pt, r->rm_encoding);
2592
                        r = r->rm_next;
2593
                }
2594
                JANUS_LOG(LOG_VERB, "       Media attributes:\n");
2595
                sdp_attribute_t *a = m->m_attributes;
2596
                while(a) {
2597
                        if(a->a_name) {
2598
                                if(!strcasecmp(a->a_name, "rtpmap")) {
2599
                                        JANUS_LOG(LOG_VERB, "         RTP Map:     %s\n", a->a_value);
2600
                                } else if(!strcasecmp(a->a_name, "crypto")) {
2601
                                        JANUS_LOG(LOG_VERB, "         Crypto:      %s\n", a->a_value);
2602
                                        if(m->m_type == sdp_media_audio || m->m_type == sdp_media_video) {
2603
                                                gint32 tag = 0;
2604
                                                int suite;
2605
                                                char crypto[40];
2606
                                                /* FIXME inline can be more complex than that, and we're currently only offering SHA1_80 */
2607
                                                int res = sscanf(a->a_value, "%"SCNi32" AES_CM_128_HMAC_SHA1_%2d inline:%40s",
2608
                                                        &tag, &suite, crypto);
2609
                                                if(res != 3) {
2610
                                                        JANUS_LOG(LOG_WARN, "Failed to parse crypto line, ignoring... %s\n", a->a_value);
2611
                                                } else {
2612
                                                        gboolean video = (m->m_type == sdp_media_video);
2613
                                                        int current_suite = video ? session->media.video_srtp_suite_in : session->media.audio_srtp_suite_in;
2614
                                                        if(current_suite == 0) {
2615
                                                                if(video)
2616
                                                                        session->media.video_srtp_suite_in = suite;
2617
                                                                else
2618
                                                                        session->media.audio_srtp_suite_in = suite;
2619
                                                                janus_sip_srtp_set_remote(session, video, crypto, suite);
2620
                                                                session->media.has_srtp_remote = TRUE;
2621
                                                        } else {
2622
                                                                JANUS_LOG(LOG_WARN, "We already configured a %s crypto context (AES_CM_128_HMAC_SHA1_%d), skipping additional crypto line\n",
2623
                                                                        video ? "video" : "audio", current_suite);
2624
                                                        }
2625
                                                }
2626
                                        }
2627
                                }
2628
                        }
2629
                        a = a->a_next;
2630
                }
2631
                if(answer && (m->m_type == sdp_media_audio || m->m_type == sdp_media_video)) {
2632
                        /* Check which codec was negotiated eventually */
2633
                        int pt = -1;
2634
                        if(!m->m_rtpmaps) {
2635
                                JANUS_LOG(LOG_VERB, "No RTP maps?? trying formats...\n");
2636
                                if(m->m_format) {
2637
                                        sdp_list_t *fmt = m->m_format;
2638
                                        pt = atoi(fmt->l_text);
2639
                                }
2640
                        } else {
2641
                                sdp_rtpmap_t *r = m->m_rtpmaps;
2642
                                pt = r->rm_pt;
2643
                        }
2644
                        if(pt > -1) {
2645
                                if(m->m_type == sdp_media_audio) {
2646
                                        session->media.audio_pt = pt;
2647
                                } else {
2648
                                        session->media.video_pt = pt;
2649
                                }
2650
                        }
2651
                }
2652
                m = m->m_next;
2653
        }
2654
}
2655

    
2656
char *janus_sip_sdp_manipulate(janus_sip_session *session, sdp_session_t *sdp, gboolean answer) {
2657
        if(!session || !session->stack || !sdp)
2658
                return NULL;
2659
        /* Placeholders for later */
2660
        sdp_attribute_t crypto_audio = {
2661
                .a_size = sizeof(sdp_attribute_t),
2662
                .a_name = "crypto",
2663
                .a_value = "audio"
2664
        };
2665
        sdp_attribute_t crypto_video = {
2666
                .a_size = sizeof(sdp_attribute_t),
2667
                .a_name = "crypto",
2668
                .a_value = "video"
2669
        };
2670
        /* Start replacing stuff */
2671
        if(sdp->sdp_connection && sdp->sdp_connection->c_address) {
2672
                sdp->sdp_connection->c_address = local_ip;
2673
        }
2674
        JANUS_LOG(LOG_VERB, "Setting protocol to %s\n", session->media.require_srtp ? "RTP/SAVP" : "RTP/AVP");
2675
        sdp_media_t *m = sdp->sdp_media;
2676
        while(m) {
2677
                m->m_proto = session->media.require_srtp ? sdp_proto_srtp : sdp_proto_rtp;
2678
                m->m_proto_name = session->media.require_srtp ? "RTP/SAVP" : "RTP/AVP";
2679
                if(m->m_type == sdp_media_audio) {
2680
                        m->m_port = session->media.local_audio_rtp_port;
2681
                        if(session->media.has_srtp_local) {
2682
                                sdp_attribute_append(&m->m_attributes, &crypto_audio);
2683
                        }
2684
                } else if(m->m_type == sdp_media_video) {
2685
                        m->m_port = session->media.local_video_rtp_port;
2686
                        if(session->media.has_srtp_local) {
2687
                                sdp_attribute_append(&m->m_attributes, &crypto_video);
2688
                        }
2689
                }
2690
                if(m->m_connections) {
2691
                        sdp_connection_t *c = m->m_connections;
2692
                        while(c) {
2693
                                c->c_address = local_ip;
2694
                                c = c->c_next;
2695
                        }
2696
                }
2697
                if(answer && (m->m_type == sdp_media_audio || m->m_type == sdp_media_video)) {
2698
                        /* Check which codec was negotiated eventually */
2699
                        int pt = -1;
2700
                        if(!m->m_rtpmaps) {
2701
                                JANUS_LOG(LOG_VERB, "No RTP maps?? trying formats...\n");
2702
                                if(m->m_format) {
2703
                                        sdp_list_t *fmt = m->m_format;
2704
                                        pt = atoi(fmt->l_text);
2705
                                }
2706
                        } else {
2707
                                sdp_rtpmap_t *r = m->m_rtpmaps;
2708
                                pt = r->rm_pt;
2709
                        }
2710
                        if(pt > -1) {
2711
                                if(m->m_type == sdp_media_audio) {
2712
                                        session->media.audio_pt = pt;
2713
                                } else {
2714
                                        session->media.video_pt = pt;
2715
                                }
2716
                        }
2717
                }
2718
                m = m->m_next;
2719
        }
2720
        /* Generate a SDP string out of our changes */
2721
        char buf[2048];
2722
        sdp_printer_t *printer = sdp_print(session->stack->s_home, sdp, buf, 2048, 0);
2723
        if(!sdp_message(printer)) {
2724
                sdp_printer_free(printer);
2725
                return NULL;
2726
        }
2727
        sdp_printer_free(printer);
2728
        char *new_sdp = g_strdup(buf);
2729
        /* If any crypto placeholer was there, fix that */
2730
        if(session->media.has_srtp_local) {
2731
                if(session->media.has_audio) {
2732
                        char *crypto = NULL;
2733
                        session->media.audio_srtp_suite_out = 80;
2734
                        janus_sip_srtp_set_local(session, FALSE, &crypto);
2735
                        /* FIXME 32? 80? Both? */
2736
                        char cryptoline[100];
2737
                        g_snprintf(cryptoline, 100, "a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:%s", crypto);
2738
                        g_free(crypto);
2739
                        new_sdp = janus_string_replace(new_sdp, "a=crypto:audio", cryptoline);
2740
                }
2741
                if(session->media.has_video) {
2742
                        char *crypto = NULL;
2743
                        session->media.video_srtp_suite_out = 80;
2744
                        janus_sip_srtp_set_local(session, TRUE, &crypto);
2745
                        /* FIXME 32? 80? Both? */
2746
                        char cryptoline[100];
2747
                        g_snprintf(cryptoline, 100, "a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:%s", crypto);
2748
                        g_free(crypto);
2749
                        new_sdp = janus_string_replace(new_sdp, "a=crypto:video", cryptoline);
2750
                }
2751
        }
2752
        return new_sdp;
2753
}
2754

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

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

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

    
2894
        /* Connect peers (FIXME This pretty much sucks right now) */
2895
        if(have_server_ip && session->media.remote_audio_rtp_port) {
2896
                server_addr.sin_port = htons(session->media.remote_audio_rtp_port);
2897
                if(connect(session->media.audio_rtp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2898
                        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);
2899
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2900
                }
2901
        }
2902
        if(have_server_ip && session->media.remote_audio_rtcp_port) {
2903
                server_addr.sin_port = htons(session->media.remote_audio_rtcp_port);
2904
                if(connect(session->media.audio_rtcp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2905
                        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);
2906
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2907
                }
2908
        }
2909
        if(have_server_ip && session->media.remote_video_rtp_port) {
2910
                server_addr.sin_port = htons(session->media.remote_video_rtp_port);
2911
                if(connect(session->media.video_rtp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2912
                        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);
2913
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2914
                }
2915
        }
2916
        if(have_server_ip && session->media.remote_video_rtcp_port) {
2917
                server_addr.sin_port = htons(session->media.remote_video_rtcp_port);
2918
                if(connect(session->media.video_rtcp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2919
                        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);
2920
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2921
                }
2922
        }
2923

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

    
3137

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